2010-08-22 111 views
0

我有一系列的水平div盒,我需要添加相关的href链接到下一个与anchorlinks。由于它们是动态生成的,我需要在JavaScript中添加href。动态添加href到链接

的预期效果将是:

<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

非常感谢

+0

你有很多'ID =页面中的“wrapper”和“id =”post2“'元素,以及其他问题:http://validator.w3.org/check?uri=http://www.warface.co.uk/clients/detail -shoppe/test-scroll&charset =(detect + automatically)&doctype = Inline&group = 0你应该修正这些...在页面加载后运行脚本运行正常,看看修复无效标记是否有助于它正确运行'document.ready '。 – 2010-08-22 11:50:20

+0

呜呜,感谢尼克的标记建议,并且效果很棒:) – Rob 2010-08-22 11:59:37

回答

3

你可以使用.attr()做这样的事情:

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

因为jQuery的1.4+,.attr()需要作出这个功能非常干净(和运行成本比较便宜)。

或者,如果你不知道职位数目(例如,他们只是不按数字顺序),可以从下一<div>得到它,就像这样:

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

你说“运行更便宜”这是什么意思?它更节省时间? – Tarik 2010-08-22 12:49:30

+0

@Braveyard - 你并没有创建另一个jQuery对象,你正在设置DOM属性,所以它的成本更低,因为它的工作量更少......所以是的,它应该更省时,除非有很奇怪的东西继续。 jQuery对象是对DOM元素的引用的数组,我们只是在数组设置属性上循环......而不是将数组中的每个引用*也*转换为jQuery对象来做一些工作......如果你不喜欢'*需要*一个jQuery对象,跳过中间人并保存一些CPU,就像你在第一个代码块中看到的那样,它也更加简洁:) – 2010-08-22 12:52:36

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

你能告诉我为什么你选择方法而不是选择方式来选择.next-video的每个元素吗? – Tarik 2010-08-22 11:10:01

+0

@Braveyard,我不明白你的问题。 – 2010-08-22 11:11:57

+0

嘿,似乎没有针对.nextvideo类,因为它没有添加href值。这是现场示例:http://www.warface.co.uk/clients/detail-shoppe/test-scroll – Rob 2010-08-22 11:18:58