Change URL parameters

前端 未结 26 2453
孤独总比滥情好
孤独总比滥情好 2020-11-22 08:40

I have this URL:

site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc

what I need is to be able to

26条回答
  •  日久生厌
    2020-11-22 09:17

    My solution:

    const setParams = (data) => {
        if (typeof data !== 'undefined' && typeof data !== 'object') {
            return
        }
    
        let url = new URL(window.location.href)
        const params = new URLSearchParams(url.search)
    
        for (const key of Object.keys(data)) {
            if (data[key] == 0) {
                params.delete(key)
            } else {
                params.set(key, data[key])
            }
        }
    
        url.search = params
        url = url.toString()
        window.history.replaceState({ url: url }, null, url)
    }
    

    Then just call "setParams" and pass an object with data you want to set.

    Example:

    $('select').on('change', e => {
        const $this = $(e.currentTarget)
        setParams({ $this.attr('name'): $this.val() })
    })
    

    In my case I had to update a html select input when it changes and if the value is "0", remove the parameter. You can edit the function and remove the parameter from the url if the object key is "null" as well.

    Hope this helps yall

提交回复
热议问题