With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
Based on @amateur's answer (and now incorporating the fix from @j_walker_dev comment), but taking into account the comment about hash tags in the url I use the following:
Edited to fix
[?|&]
in regex which should of course be[?&]
as pointed out in the commentsEdit: Alternative version to support removing URL params as well. I have used
value === undefined
as the way to indicate removal. Could usevalue === false
or even a separate input param as wanted.See it in action at https://jsfiddle.net/bp3tmuxh/1/
Here's an alternative method using the inbuilt properties of the anchor HTML element:
if you want to set multiple parameters at once:
same function as @amateur's
if jslint gives you an error add this after the for loop
Here's my approach: The
location.params()
function (shown below) can be used as a getter or setter. Examples:Given the URL is
http://example.com/?foo=bar&baz#some-hash
,location.params()
will return an object with all the query parameters:{foo: 'bar', baz: true}
.location.params('foo')
will return'bar'
.location.params({foo: undefined, hello: 'world', test: true})
will change the URL tohttp://example.com/?baz&hello=world&test#some-hash
.Here is the
params()
function, which can optionally be assigned to thewindow.location
object.Yeah I had an issue where my querystring would overflow and duplicate, but this was due to my own sluggishness. so I played a bit and worked up some js jquery(actualy sizzle) and C# magick.
So i just realized that after the server has done with the passed values, the values doesn't matter anymore, there is no reuse, if the client wanted to do the same thing evidently it will always be a new request, even if its the same parameters being passed. And thats all clientside, so some caching/cookies etc could be cool in that regards.
JS:
HTML:
C#:
No duplicates, each request as unique as you modified it, and due to how this is structured,easy to add more queries dynamicaly from wthin the dom.
My take from here (compatible with "use strict"; does not really use jQuery):
Example usage: