2015-09-25 46 views
0

我还在学习,所以我在绞尽脑汁。div的重复ID

$('.post-outer .post-footer .post-footer-line.post-footer-line-2 .post-labels a').each(function(index, el) { 
    $('.post-outer').attr('itemtype', $(this).attr('href')); 
}); 

当你运行上面的JS时,它只需要在其他“DIV”中重复的第一个“href”。这是怎么回事:

<div class="post-outer" id="001" itemtype="url1">test1</div> 
<div class="post-outer" id="002" itemtype="url1">test2</div> 
<div class="post-outer" id="003" itemtype="url1">test3</div> 

我想发生这样的:

<div class="post-outer" id="001" itemtype="url1">test1</div> 
<div class="post-outer" id="002" itemtype="url2">test2</div> 
<div class="post-outer" id="003" itemtype="url3">test3</div> 

在这里的例子,它只是需要在最后一个div和其他 https://jsfiddle.net/mpb9wfmc/

+0

你能添加你的html代码吗? – Diptox

+0

https://jsfiddle.net/mpb9wfmc/ –

+0

https://jsfiddle.net/mpb9wfmc/2/这里是 – Diptox

回答

1

使用.each你可以使用重复this为当前元素重复:

$(this).attr('itemtype', newValueHere); 

这样做$('.post-outer').attr('itemtype', $(this).attr('href'));将应用于所有类post-outer的项目。

+0

但我怎么能做到这一点? https://jsfiddle.net/mpb9wfmc/ –

+0

@MateusBatista你只需要做'$(this).attr('itemtype',$(this).attr('href'));'。 [示例小提琴](https://jsfiddle.net/mpb9wfmc/3/)。 –