2015-09-25 98 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/)。 –