如何使用jQuery附加到超链接?

时间:2011-06-03 22:00:40

标签: jquery

我希望将"&location=/xyz/123"添加到页面上每个超链接的末尾。

我该怎么做呢?我对jQuery有点新鲜

我在想这样的事,但我不是100%

<script type="text/javascript">
jQuery(document).ready(function(){
   jQuery('a').attr('href').append("&location=/xyz/123");
});
</script>

谢谢。

3 个答案:

答案 0 :(得分:2)

attr函数用作访问器时返回一个字符串。字符串上没有append函数。你可能意味着:

<script type="text/javascript">
jQuery(document).ready(function(){
   jQuery('a[href]').attr('href', function(index, attr) {
        return attr + "&location=/xyz/123";
   });
});
</script>

它附加到每个具有一个链接的href(注意我已经更改了选择器,因此我们忽略了没有href s的锚点)。它使用接受函数的the feature of the attr function并使用每个元素调用它,然后使用函数的返回值在元素上设置属性(在您的情况下为href)。

答案 1 :(得分:-1)

希望这适合你。

修改

<script type="text/javascript">
jQuery(document).ready(function(){
   jQuery('a').attr('href', function(i,val){
    return val+"&location=/xyz/123"
   })
});
</script>

答案 2 :(得分:-1)

jQuery(document).ready(function() {
    jQuery('a[href]').each(function() {
        $(this).attr('href', $(this).attr('href') + "&location=/xyz/123");
    });
});

(将[href]添加到初始选择器,这样就不会点击锚元素了)