Jquery 如何检查URL上是否有字符串/参数,如果没有,则添加该字符串/参数
我有一个jQuery,它从表单选择选项中获取参数,并将其添加到URL中进行搜索。但是现在,我的JS删除了旧的东西,并用新的东西替换。这是当前的一个:Jquery 如何检查URL上是否有字符串/参数,如果没有,则添加该字符串/参数,jquery,url,Jquery,Url,我有一个jQuery,它从表单选择选项中获取参数,并将其添加到URL中进行搜索。但是现在,我的JS删除了旧的东西,并用新的东西替换。这是当前的一个: $("#year").change(function() { var path = $(location).attr('href').split('?', 1);; var year = $(this).val(); var search = path + '?year=' + year;
$("#year").change(function() {
var path = $(location).attr('href').split('?', 1);;
var year = $(this).val();
var search = path + '?year=' + year;
if ($(this).val() != '') {
window.open(search, '_self');
}
});
$("#type").change(function() {
var path = $(location).attr('href').split('?', 1);;
var type = $(this).val();
var search = path + '?type=' + type;
if ($(this).val()) {
window.open(search, '_self');
}
});
因此,如果用户从另一个选项中选择,则会是:www.domain.com/search?type=something或www.domain.com/search?year=2011
但我想做的是,用户可以选择这两个参数。所以URL可以是www.domain.com/search?type=something&year=2011,但我不知道怎么做
我尝试了一些东西,但它总是在末尾添加新的参数,结果URL是这样的:www.domain.com/search?type=something&year=2011&type=something&year=2011&type=something&year=2011&type=something&year=2011&year=2011&type=something&year=2011
谢谢你的帮助 您可以将所有当前查询字符串解析为一个对象/数组,然后更新或添加到该对象,最后从该对象构建新的查询字符串。这将确保每个都有一个,并且它们被正确设置。您可以使用regexp对象并解析
&
和的查询字符串?
以了解是否存在一些参数
下面是main idea()的js代码:
function replaceorad(str、pattern、newValue){
如果(str.match(模式)){
//参数已定义
document.writeln(str.replace(pattern,newValue)+'
');
}
else if(str.indexOf(“?”)=-1){
//查询字符串存在,但没有此参数
document.writeln(str+“&+newValue+”
);
}
否则{
//没有查询字符串
document.writeln(str+“?”+newValue+'
');
}
}
var str=[“www.domain.com/search?type=something&year=2011”,
“www.domain.com/search?year=2011&type=something”,
“www.domain.com/search?type=something”,
“www.domain.com/search?year=2011”,
“www.domain.com/search”];
var patt1=/type=[^&^$]+/i;
var patt2=/year=[^&^$]+/i;
var newValue1=“type=new”
var newValue2=“年份=1999”
对于(变量i=0;i ”);
对于(变量i=0;i
function replaceOrAdd(str, pattern, newValue) {
if (str.match(pattern)) {
// parameter is already defined
document.writeln(str.replace(pattern, newValue) + '<br />');
}
else if (str.indexOf("?") != -1) {
// query string exists, but without this parameter
document.writeln(str + "&" + newValue + '<br />');
}
else {
// there is no query string
document.writeln(str + "?" + newValue + '<br />');
}
}
var str = ["www.domain.com/search?type=something&year=2011",
"www.domain.com/search?year=2011&type=something",
"www.domain.com/search?type=something",
"www.domain.com/search?year=2011",
"www.domain.com/search"];
var patt1 = /type=[^&^$]+/i;
var patt2 = /year=[^&^$]+/i;
var newValue1 = "type=new"
var newValue2 = "year=1999"
for (var i = 0; i < str.length; i++) {
replaceOrAdd(str[i], patt1, newValue1);
}
document.write("<br/>");
for (var i = 0; i < str.length; i++) {
replaceOrAdd(str[i], patt2, newValue2);
}