我一直在打扰我的头.
使用jQuery或javascript,如何切换变量&值然后重建查询字符串?例如,我的起始网址是:
http://example.com?color=red&size=small,medium,large&shape=round
然后,如果用户点击标有“红色”的按钮,我想要结束:
http://example.com?size=small,large&shape=round //color is removed
然后,如果用户再次点击“红色”,large&shape=round&color=red //color is added back
然后,如果用户点击标有“medium”的按钮,large&shape=round&color=red //medium is removed from list
然后,如果用户再次点击标签的“媒体”,large,medium&shape=round&color=red //medium added back
变量所在的顺序并不重要;我刚刚把它们抓到最后.
解决方法
function toggle(url,key,val) { var out = [],upd = '',rm = "([&?])" + key + "=([^&]*?,)?" + val + "(,.*?)?(&.*?)?$",ad = key + "=",rmrplr = function(url,p1,p2,p3,p4) { if (p2) { if (p3) out.push(p1,'=',p3.substr(1)); else out.push(p1,p2.substr(0,p2.length - 1)); } else { if (p3) out.push(p1,p3.substr(1)); else out.push(p1); } if (p4) out.push(p4); return out.join('').replace(/([&?])&/,'$1').replace(/[&?]$/,''); //<!2 },adrplr = function(s) { return s + val + ','; }; if ((upd = url.replace(new RegExp(rm),rmrplr)) != url) return upd; if ((upd = url.replace(new RegExp(ad),adrplr)) != url) return upd; return url + (/\?.+/.test(url) ? '&' : '?') + key + '=' + val; //<!1 }
params自我描述够了,希望这个帮助.
!1:从…改变? ‘&安培;’ : ” 至 … ? ‘&安培;’ :’?’
!2:从.replace(‘?&’,’?’)更改为.replace(/([&?]&)/,’$1′)…