开发者

Howto attach a parameter to a link without id or class using jQuery?

开发者 https://www.devze.com 2023-01-23 12:13 出处:网络
I have three links that unfortunately do not have a class or an id. Their href is static. I want to attach the same parameter to all three of them at the end of the URL, so my idea is to identify them

I have three links that unfortunately do not have a class or an id. Their href is static. I want to attach the same parameter to all three of them at the end of the URL, so my idea is to identify them based on their href value but I do not know how to do this.

The links look like:

<ul class="links primary-tabs">
   <li><a href="/user">Login</a></li>
   <li><a href="/user/register">Register</a></li>
   <li><a href="/user/password">Forgot Password</a></li>
</ul>

So far I have the following code where $destination is a PHP variable:

$(document).ready(function(){
        $(".page-user .primary-tabs a").attr("href", "/user/register?destination='.$destination.'");
});

This would, of course, change all of the three links to /user/register?destination=....

Can anyone help me out on how to attach 开发者_StackOverflow中文版$destination to all of the three links preserving their original href?

Thanks


You can use .attr() with a function, like this:

$(document).ready(function(){
  $(".page-user .primary-tabs a").attr("href", functon(i, href) {
     return href + "?destination='.$destination.'";
  });
});

This just appends that querystring to each, href being the previous value inside the loop.


Use each and this:

<html><head></head><body>
<ul class="links primary-tabs">
   <li><a href="/user">Login</a></li>
   <li><a href="/user/register">Register</a></li>
   <li><a href="/user/password">Forgot Password</a></li>
</ul>
<script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>
<script>
$(document).ready(function(){
    $("ul.primary-tabs a").each(function(){
        $(this).attr("href",$(this).attr('href') + '?destination=foo');
    });
});
</script>
</body></html>
0

精彩评论

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