2016-08-27 106 views
0

Jquery超級新手。需要幫助創建使用循環的唯一ID - jQuery

我想通過創建一個循環來使用jquery爲每個「section」標籤創建唯一的id。出於某種原因,以下代碼無法正常工作,而且我感到非常困惑,所以請讓我知道,如果您有任何想法我做錯了什麼。
此外,我試圖讓我的標籤裏面的h2標籤,然後讓我的標籤裏面的ul標籤。任何幫助都會受到讚賞。所有這些信息都應該在我的h1標籤後添加。 謝謝

$(document).ready(function() { 
    var h2 = $("h2"); 
    $(h2).each(function(index) { 
     for (var index = 0; index < 4; index++) { 
      $(h2).attr("id", "section" + index); 

      $(h2).attr("href", "#"); 
     } 
    }); 

    var ul = $("<ul></ul>").find("ul"); 
    var list = $("<li></li>").find("li"); 

    $(".content h1").append(h2); 

}); 

HTML ADDITION 

<body> 
<div class="concha"> 
<h1>The love of my life and how we met </h1> 

    <h3>The following is information on the Best thing that's ever  happened to me</h3> 
    <h2>We met at the Park</h2> 
    <p>filler text</p> 
    <p>filler text</p> 

    <h2>We went to the movies</h2> 
    <p>filler text</p> 
    <p>filler text</p> 
    <h2>We had ice cream together</h2> 
     <p>filler text</p> 
     <p>filler text</p> 
    <h2>The end</h2> 
     <p>filler text</p> 
    <p>filler text</p> 
+0

你能分享你的html嗎? –

+0

您的所有h2標籤都以id =「section3」結尾了嗎? –

+0

是的,但我試圖讓它成爲第0節,第1節,第2節,第3節或至少某種類型的唯一ID –

回答

3

你是通過你的h2元素循環兩次。此外,您正在編寫循環中的所有h2元素。您需要在循環中使用this來調用當前元素:

$(document).ready(function() { 
    var h2 = $("h2"); 
    var i = 0; // define variable i as your "index" 
    $(h2).each(function(index) { 
     i++; // Increase i by 1 each time you loop through your h2 elements 
     $(this).attr("id", "section" + i); // Use $(this) to pull out the current element 

     $(this).attr("href", "#"); // Again, use $(this) 
    }); 

});