我的网址看起来像这样
/ myurl?code1 = abcde& code2 = fghijk& code3 = lmnop& code4 = qrstu& code5 = vwxyz(最多5个代码变量)
我有一个onclick事件,我得到代码变量,例如在上面的示例中它返回'fghijk',但我不知道参数,例如code2。所以我想做两件事:
1)查找并删除参数&来自我的网址的值(如果我的onclick变量返回'fghijk',在上面的示例中我的网址变为,/ myurl?code1 = abcde& code3 = lmnop& code4 = qrstu& code5 = vwxyz)
2)之后我想重置参数号码,以便我的代码参数从1开始顺序,所以在上面的数字1执行后我的url应该变为/ myurl?code1 = abcde& code2 = lmnop&安培; CODE3 = qrstu&安培;码4 = VWXYZ
$('.myelement').on('click', function() {
var url = $('.myelement a').attr('href');
var codevar = $('.myelement span').text();
if(url +'contains('+codevar+')') {
// strip the param and variable from the url here
// now reset the url so code params are in number sequence
}
});
答案 0 :(得分:1)
$('.myelement').on('click', function() {
var url = $('.myelement a').attr('href');
var codevar = $('.myelement span').text();
if(url.match(codevar)) {
var queryString = url.substring(url.indexOf("?") + 1);
var params = queryString.split("&");
var codeIndex = 1;
var newQuery = "";
for (var i = 0; i < params.length; i++) {
if (!params[i].match(codevar)) {
newQuery += params[i].replace(/code[0-9]/, "code" + codeIndex);
codeIndex++;
if (i < params.length - 1) {
newQuery += "&";
}
}
}
url = url.replace(queryString, newQuery).replace(/&$/, ""); //new query string with the sequential parameters
}
});
希望这有帮助。
此致
马塞洛
答案 1 :(得分:1)
var codevar = 'fghijk';
var url = $('.myelement a').attr('href');
var param = '&'+url.substring(url.indexOf('?')+1);
url = url.substring(0,url.indexOf('?')+1);
if(param.indexOf(codevar) > -1) {
var arr = param.split("&code");
param = '';
for(var i = 1;i<arr.length;i++){
if(codevar == arr[i].substring(2))
arr.splice(i, 1);
param += 'code'+i+'='+arr[i].substring(2);
if(i != arr.length-1)
param +='&';
}
$('.myelement a').attr('href',url+param);
示例:
答案 2 :(得分:0)
您可以将param作为键拆分。
var el = $('.myelement'),
out = $("#output");
el.on('click', function (ev) {
ev.preventDefault();
var href = el.find("a").prop("href"),
param = el.find("span").text(),
idx = href.indexOf(param),
arr = [], url;
if (idx > -1) {
arr = href.split(param); // split href[0] param href[1]
url = arr.join("mynewvalue");
out.text(url);
}
});