开发者

How do I append to a hyperlink using jQuery?

I am looking to add "&location=/xyz/123" to the end of every hyperlink on a page.

How do I go about doing this? I am somewhat new to jQuery

I am t开发者_开发问答hinking something like this but I am not 100%

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

Thank you.


The attr function, when used as an accessor, returns a string. There's no append function on strings. You probably mean:

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

That appends to the href of every link that has one (note I've changed the selector so we ignore anchors that don't have hrefs). It uses the feature of the attr function that accepts a function and calls it with each element, then uses the return value of the function to set the attribute (in your case, href) on the element.


Hope this works for you.

Edit

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


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

(adding [href] to the initial selector so you don't hit anchor elements)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜