将href动态添加到链接 [英] Add href to links dynamically

查看:371
本文介绍了将href动态添加到链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列的水平div框,我需要添加相关的href以便使用定位链接链接到下一个.由于它们是动态产生的,因此我需要使用JavaScript添加href.

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.

所需的效果将是:

<div id="post1">
<a class="next-video" href="#post2">NextVideo</a>
</div>

<div id="post2">
<a class="next-video" href="#post3">NextVideo</a>
</div>

添加了脚本

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

但似乎没有针对.next-video类,这是实时版本: http://www.warface.co.uk/clients/detail- shoppe/test-scroll

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

非常感谢

推荐答案

您可以使用 .attr() :

You could do something like this using .attr():

$("a.next-video").attr('href', function(i) {
  return '#post' + (i+2);       
});

从jQuery 1.4开始, .attr() 的功能使其变得非常干净(而且更便宜)运行).

Since jQuery 1.4+, .attr() takes a function making this very clean (and cheaper to run).

或者如果您不知道帖子编号(例如,它们不是按数字顺序排列的),则可以从下一个<div>获取它,如下所示:

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');
});

这篇关于将href动态添加到链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆