2016-09-27 31 views
0

迭代遍歷相同類的html元素我有一些具有相同類的div元素。我想遍歷它們。我使用jquery「.each」來完成它。我也想要單獨訪問每個元素,並通過它來調用它的類,以便我需要獲取類元素數組中元素的索引。目前,我有一個類似的代碼:使用.each

$('.the_div_class').each(function(i, obj) { 

    if("a certain condition") { 

    $('.the_div_class')[0].toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class; 

    } 

} 

但是我收到一個錯誤說「$(...)[0] .toggleClass不是一個函數」。如果我不指定索引我的toogle陣列中的所有元素......我CONSOLE.LOG的「$(」 the_div_class。)」數組,並得到類似這樣的結構:

[div.the_div_class, div.the_div_class, div.the_div_class, div.the_div_class, div.the_div_class, prevObject: r.fn.init[1]] 

而且如果我CONSOLE.LOG「$(」。the_div_class')[0]」我得到這個:

<div class="the_div_class"> 

爲什麼它不工作,我應該爲了使其發揮作用呢?

回答

2

代碼$('.the_div_class')[0]將只能得到該選擇匹配與類DOM的天真,這是行不通的,因爲它不再是一個jQuery對象的第一個元素(因此它沒有方法.toggleClass()) 。裏面.each()可以使用this來指代當前元素被迭代:

$('.the_div_class').each(function(i, obj) { 

    if("a certain condition") { 

    $(this).toggleClass('other_div_class'); 

    } 

} 

:要通過的指數在jQuery中可以使用.get()拿到項目。例如:

$('.the_div_class').get(0).toggleClass('other_div_class'); 
0

當您指定索引時,您將獲取使用jQuery選擇的純javascript元素,而不是jQuery對象。這就是爲什麼toggleClass()方法對您不可用。

你可以將它包裝在jQuery中,像這樣$($(selector)[i])將其轉換回jQuery對象。但是,每個循環提供的參數都是你的朋友。也就是說,您可以使用$(obj)訪問循環中的當前對象。

1

你的代碼更改爲:

var collection = $('.the_div_class'); 
collection.each(function(i, obj) { 

    if("a certain condition") { 
     $(collection[0]).toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class; 
    } 
} 

你需要再次通過DOM元素$重新jQuery對象,即$(「。the_div_class' $()[0])爲您的代碼。

0

您需要更改代碼,通過使用這個關鍵字來獲得元素:

$('.the_div_class').each(function(i, obj) { 
    if("a certain condition") { 
    $(this).toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class; 
    } 
}