Add href to links dynamically
I have a series of horizontal div boxes that I need to add the relevant href to link to the next one with anchorlinks. As they are produced dynamically I need to add the href with JavaScript.
The desired effect will be:
<div id="post1">
<a class="next-video" href="#post2">NextVideo</a>
</div>
<div id="post2">
<a class="next-video" href="#post3">NextVideo</a>
</div>
Added the script
$('.next-video').each(function(in开发者_JS百科dex) {
$(this).attr('href', '#post' + (index + 2));
});
but doesn't seem to target the .next-video
class, this is the live version:
http://www.warface.co.uk/clients/detail-shoppe/test-scroll
Many thanks
You could do something like this using .attr()
:
$("a.next-video").attr('href', function(i) {
return '#post' + (i+2);
});
Since jQuery 1.4+, .attr()
takes a function making this very clean (and cheaper to run).
Or if you don't know the post number (e.g. they're just not in numerical sequence), you can get it from the next <div>
, like this:
$("a.next-video").attr('href', function(i) {
return '#' + $(this).parent().next("div[id^='post']").attr('id');
});
$('.next-video').each(function(index) {
$(this).attr('href', '#post' + (index + 2));
});
精彩评论