2011-04-18 57 views
2

我正在迭代jQuery中的一系列元素(故意地)。

所以基本上我想是這樣的,但正確的語法:

$(".sonicrow").each(function() { 
    $(this + 'somediv').css('background-color', 'red'); 
}); 

顯然,這是某種對象/字符串混雜的。訪問此對象中特定的somediv的正確語法是什麼?

謝謝, 約翰。

回答

5
$(".sonicrow").each(function() { 
    $('somediv', this).css('background-color', 'red'); 
}); 

其中第二個參數是選擇器的「上下文」。因爲你的somediv必須是.somediv如果它是一個類或#somediv如果它是一個id。

這個問題是關係到How to get the children of the $(this) selector?其中也包含這個答案

... 
    $(this).find('somediv').css(...) 
... 

根據jQuery context selector$(selector, context)$(context).find(selector)實現。

+0

但不是'$(this).find('somediv')。css(...)'比第一個慢? – 2011-04-18 06:14:00

+0

@experimentX看到我最新的答案。根據jQuery文檔,他們是等效的:) – 2011-04-18 06:16:06

+0

嗯,...我想那麼。 – 2011-04-18 06:17:22

1

試試這個:

$(".sonicrow").each(function() { 
    $(this).find('somediv').css('background-color', 'red'); 
}); 
1
$(".sonicrow").each(function() { 
    $(this).find('.somediv').css('background-color', 'red'); 
}); 

你可以做到這樣。

0

算法:

HTML結構爲樹形結構。因此,當您參考$(".sonicrow")時,您可以使用「sonicrow」作爲類名稱訪問節點。現在,你需要搜索的子節點是一個div ...

所以,你的代碼將是這樣的:

  1. 查找其元素「sonicrow」類名
  2. 發現任何兒童元素,它的類型爲 「格」 ...
  3. 應用CSS

解決方案:

查找有 「sonicrow」 作爲類名的節點的引用:var route=$(".sonicrow");

尋子節點是一個div:var desiredChild = route.find("div");

應用CSS:desiredChild.css("property","value"); ...


合併到這一點的jQuery鏈:

$(".sonicrow").find("div").css('background-color', 'red'); 

但要重複這一過程,其中有「sonicrow」類名稱的每一個元素,所以你必須循環並且代碼:

$(".sonicrow").each(function() 
{ 
    $(this).find("div").css('background-color', 'red'); 
}); 

PS我在這裏使用了$(this),因爲$(「。sonicrow」)已經返回一個對象,並且您正在遍歷該特定對象,因此您必須使用"this" variable指向該元素。

在另一方面,你正在使用jQuery所以$(本)給你一個jQuery對象來解決這個,否則你不得不使用基本JavaScript語法,如:this.style.css.property=value語法:-)

我希望你有得到你的答案...

相關問題