将数据从下拉列表添加到字符串

时间:2010-11-24 08:06:05

标签: javascript jquery

我有一个带查询字符串
的网址 (例如:http://www.example.com/?page=index&opr=sales-current&pageno=1

我需要使用javascript或jQuery将“opr”值从“sales-current”更改为“sales- [dropdown value]”

由于

3 个答案:

答案 0 :(得分:1)

这是另一种方法。代码有点长,因为解析搜索字符串以创建参数的映射然后再次一起构建(这应该适用于任何参数):

var searchTerms = document.location.search.substr(1).split('&');
var parameters = {};
for(var i = 0; i < searchTerms.length; i++) {
    var parts = searchTerms[i].split('=', 2);
    parameters[parts[0]] = parts[1];
}

parameters['opr'] = 'sales-' + document.getElementById('selectboxID').value;

searchTerms = [];
for(var key in parameters) {
    if(parameters.hasOwnProperty(key)) {
        searchTerms.push(key + '=' + parameters[key]);
    }
}

document.location.search = searchTerms.join('&');

参考:document.location

Working Demo(我只使用jQuery进行演示,实际代码如上所示)

答案 1 :(得分:0)

Url = document.location.href.split("?");  
dropdownval = document.getElementByID('dropdown/selectbox id tag').value;  
document.location = Url[0]+'?page=index&opr=sales-'+dropdownval+'&page=1';  

这是您可以用来实现此目的的代码。

答案 2 :(得分:0)

或者你可以做替换:

var val = 'sales-' + document.getElementById('selectBox').value;
document.location.href = document.location.href.replace(/([?&]opr=)([^&]+)/, '$1' + val);

opr参数替换为val的值(#selectBox)。

然而,我相信@Felix Kling的solution更通用。只是张贴以提示一个简单的解决方案。