0

我想为我网站中的每个链接添加一个参数,比如说 ?var=123 。

我尝试使用这些代码,但什么也没发生:

var has_querystring = /\?/; 

$("a[href]").each(function(el) {
    if ( el.href && has_querystring.test(el.href) ) {
        el.href += "&var=123";
    } else {
        el.href += "?var=123";
    }
});

$('a[href]').attr('href', function(i, hrf) { return hrf + '?var=123';});

$('a[href]').click(function(e) {
    e.preventDefault();
    window.location = this.href + '?var=123';
});`

我究竟做错了什么?谢谢你。

4

1 回答 1

1

If none of those worked then it sounds like your jQuery code is executing before the DOM has finished being constructed, and it's not selecting any of the elements. The solution to that is to use a DOM ready event handler:

$(document).ready(function() {
    // your code here
});

In the case of the first snippet, using .each(), note that the first argument passed to the function is the index of the element, not the element itself, so you actually want:

$('a[href]').each(function(index, el) {
    ...
});
于 2013-03-31T23:41:59.257 回答