动态添加href到链接

我有一系列水平div框,我需要添加相关的href链接到下一个与锚链接。 因为它们是动态生成的,所以我需要使用JavaScript添加href。

期望的效果是:

  

添加了脚本

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

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

非常感谢

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

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

由于jQuery 1.4 +,。attr .attr()采用了一个function,使得它非常干净(并且运行起来更便宜)。

或者,如果您不知道post编号(例如,他们不是数字序列),您可以从下一个

获取它,如下所示:

 $("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)); });