简体   繁体   English

将href动态添加到链接

[英]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. 我有一系列的水平div框,我需要添加相关的href以便通过anchorlinks链接到下一个。 As they are produced dynamically I need to add the href with JavaScript. 由于它们是动态产生的,因此我需要使用JavaScript添加href。

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(index) {
    $(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 但似乎没有针对.next-video类,这是实时版本: http : //www.warface.co.uk/clients/detail-shoppe/test-scroll

Many thanks 非常感谢

$('.next-video').each(function(index) {
    $(this).attr('href', '#post' + (index + 2));
});

You could do something like this using .attr() : 您可以使用.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). 从jQuery 1.4开始, .attr()接受了一个使它非常干净(且运行起来更便宜.attr()的函数。

Or if you don't know the post number (eg they're just not in numerical sequence), you can get it from the next <div> , like this: 或者,如果您不知道帖子编号(例如,它们不是按数字顺序排列的),则可以从下一个<div>获取它,如下所示:

$("a.next-video").attr('href', function(i) {
  return '#' + $(this).parent().next("div[id^='post']").attr('id');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM