我有一个充满链接的页面。我正在尝试在每个结尾处添加一个查询字符串,以便:
http://www.example.com?x=1&y=2变为http://www.example.com?x=1&y=2&z=3
我想解析每个链接并添加它。我似乎无法使用jQuery找到一种优雅的方式 - 任何帮助都会非常感激。
答案 0 :(得分:2)
这样的事情应该有效
$('a').each(function() {
$(this).prop('href',$(this).prop('href') + '&z=3');
})
循环每个a
元素并将z=3
添加到href
属性的末尾
答案 1 :(得分:1)
$("a").attr('href', function(c, b) {
return b + "&z=3";
});
答案 2 :(得分:1)
$('a[href^="http://www.example.com"]').prop('href', function(i, href){
return href + '&z=3';
})
答案 3 :(得分:0)
这应该可以解决问题。
$('a').each(function(){
this = $this;
curr_url = this.attr('href');
this.attr('href', 'curr_url' + '&z=3');
});
答案 4 :(得分:0)
你需要检查this.attr('href')。indexOf('?')>在添加键/值对之前为-1。如果没有'?'你也需要添加它。
最好在javascript中使用原生href API来解析URL,然后将所需的位添加到需要修改的URL部分。
http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
您可能还应该考虑使用“on”事件触发器(jQuery latest)来执行此操作。当对很多元素进行操作时,增加DOM的速度很慢,并且如果在onLoad钩子中添加,则会延迟页面显示。
$('body').on('click','a',function(e){
// Prevent it jumping straight out
e.preventDefault;
// Define vars
var href = this.href,
qstr = 'a=b&bar=foo';
// check for structure of url and add query string
this.href += ((href.indexOf('?') > -1) ? '&': '?') + qstr;
// jump
return true;
});