如何在 URL 中添加参数? [英] How to add a parameter to the URL?
问题描述
我当前的网址是:http://something.com/mobiles.php?brand=samsung
现在,当用户点击最低价格过滤器(比如 300)时,我希望我的 URL 变成
Now when a user clicks on a minimum price filter (say 300), I want my URL to become
http://something.com/mobiles.php?brand=samsung&priceMin=300
换句话说,我正在寻找一个 javascript 函数,它将在当前 URL 中添加一个指定的参数,然后将网页重定向到新的 URL.
In other words, I am looking for a javascript function which will add a specified parameter in the current URL and then re-direct the webpage to the new URL.
注意:如果没有设置参数,那么函数应该添加?
而不是&
Note: If no parameters are set then the function should add ?
instead of &
即如果当前 URL 是 http://something.com/mobiles.php
那么页面应该重定向到 http://something.com/mobiles.php?priceMin=300代码>而不是
http://something.com/mobiles.php&priceMin=300
i.e. if the current URL is http://something.com/mobiles.php
then page should be re-directed to http://something.com/mobiles.php?priceMin=300
instead of http://something.com/mobiles.php&priceMin=300
推荐答案
尝试这样的事情,它也应该考虑在 url 中已经有该参数的情况:
try something like this, it should consider also cases when you already have that param in url:
function addOrUpdateUrlParam(name, value)
{
var href = window.location.href;
var regex = new RegExp("[&\?]" + name + "=");
if(regex.test(href))
{
regex = new RegExp("([&\?])" + name + "=\d+");
window.location.href = href.replace(regex, "$1" + name + "=" + value);
}
else
{
if(href.indexOf("?") > -1)
window.location.href = href + "&" + name + "=" + value;
else
window.location.href = href + "?" + name + "=" + value;
}
}
然后你像你的情况一样调用它:
then you invoke it like in your case:
addOrUpdateUrlParam('priceMin', 300);
这篇关于如何在 URL 中添加参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!