2014-01-23 52 views
0
I have a document structure that looks similar to this: 

<article id="post1" class="post-5 page type-page" > 
    <section class = "holder clearfix"> 

    <div class = "four columns"> 
     <a title class = "single-image short-link" href "http://whatever.com" target = "self"> 
     </a> 
    </div> 

    <div class = "four columns"> 
     <a title class = "single-image short-link" href "http://whatever.com" target = "self"> 
     </a> 
    </div> 

    <div class = "four columns"> 
     <a title class = "single-image short-link" href "http://whatever.com" target = "self"> 
     </a> 
    </div> 

    <div class = "four columns"> 
     <a title class = "single-image short-link" href "http://whatever.com" target = "self"> 
     </a> 
    </div> 


</section> 
</article> 

元素嵌套元素我想要做的就是添加一個div類和一個唯一的ID給每個使用JQuery一個元素。添加使用JQuery

最終的結果會是這個樣子

<article id="post1" class="post-5 page type-page" > 
    <section class = "holder clearfix"> 

    <div class = "four columns"> 
     <a title class = "single-image short-link" href "http://whatever.com" target = "self"> 

      <div id="button1" class = "shiny-button"> </div>  // unique ID 
     </a> 
    </div> 

    <div class = "four columns"> 
     <a title class = "single-image short-link" href "http://whatever.com" target = "self"> 

      <div id="button2" class = "shiny-button"> </div>  // unique ID 
     </a> 
    </div> 

    <div class = "four columns"> 
     <a title class = "single-image short-link" href "http://whatever.com" target = "self"> 
      <div id="button3" class = "shiny-button"> </div>  // unique ID 
     </a> 
    </div> 

    <div class = "four columns"> 
     <a title class = "single-image short-link" href "http://whatever.com" target = "self">  
      <div id="button4" class = "shiny-button"> </div>  // unique ID 
     </a> 
    </div> 


</section> 
</article> 

到目前爲止,下面的jQuery代碼讓我大約走了一半:

$('<div/>', { 
    class:'shiny-button', 
}).appendTo('.single-image'); 

我試着用代碼打,看起來類似於以下但我似乎無法得到它的權利

$('<div/>', { 
    class:'shiny-button', 
    id: 'button1', 
}).appendTo('.holder .four:nth-child(1)'); 

謝謝。

回答

0

嘗試使用每個。所以

$('.single-image').each(function(index){ 
    //Append new element to $(this) 
    //index will be a counter 
    //$(this) = the current $('.single-image') element 
}); 

我相信你可以使用索引是唯一的。我不記得,但.each()函數記錄在jQuery中。

0

嘗試

$('#post1 .single-image').append(function(i){ 
    return '<div id="button'+(i+1)+'" class = "shiny-button"> dd</div>' 
}) 

演示:Fiddle