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>
精彩评论