2016-05-25 63 views
-2

我正在循環某個div的子項。

根據孩子是否奇怪或者我有不同的以下操作。

我想使用jQuery的$(this)來獲取當前的上下文並添加到查詢,具體取決於它的狀態是奇數還是偶數。

如果它是一個偶兒,我想要得到該div的孩子(所以這是一個孩子從循環)。我怎樣才能做到這一點?

我目前的方法是行不通的

$("div.profile_result").children().each(function(a){ 
// This way of adding the child a doesn't work 
if (a%2) console.log($($(this) + " > a")) 


else console.log("info") 
}) 
+0

讓我們看看HTML,當你說奇或偶,你的意思是數或指數? – JordanHendrix

+0

問題出在'$($(this)+「> a」))'部分。我有奇怪的東西在工作。 – chackerian

+0

聽起來你想選擇'$('div.profile_result>:even> a')'。 – zzzzBov

回答

1

$($(this) + " > a")試圖來連接對象和一個你不能做的字符串。

使用$(this).find('a')代替

0

您可以使用$(本)的.index(),以確定它是否是奇數還是偶數

$("div.profile_result").children().each(function(a){ 
// This way of adding the child a doesn't work 
var el = $(this); 
var el_index = el.index();//node the index starts from 0; 
if ((el_index+1)%2 == 0) 
    console.log(el.children()); // this is even 
else 
    console.log("info"); 
}); 
+0

'a'已經是索引。爲什麼回到dom去獲取'each'已經提供的東西? OP的問題與獲取索引值無關 – charlietfl