我正在迭代jQuery中的一系列元素(故意地)。
所以基本上我想是這樣的,但正確的語法:
$(".sonicrow").each(function() {
$(this + 'somediv').css('background-color', 'red');
});
顯然,這是某種對象/字符串混雜的。訪問此對象中特定的somediv的正確語法是什麼?
謝謝, 約翰。
我正在迭代jQuery中的一系列元素(故意地)。
所以基本上我想是這樣的,但正確的語法:
$(".sonicrow").each(function() {
$(this + 'somediv').css('background-color', 'red');
});
顯然,這是某種對象/字符串混雜的。訪問此對象中特定的somediv的正確語法是什麼?
謝謝, 約翰。
$(".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)
實現。
試試這個:
$(".sonicrow").each(function() {
$(this).find('somediv').css('background-color', 'red');
});
$(".sonicrow").each(function() {
$(this).find('.somediv').css('background-color', 'red');
});
你可以做到這樣。
算法:
HTML結構爲樹形結構。因此,當您參考$(".sonicrow")
時,您可以使用「sonicrow」作爲類名稱訪問節點。現在,你需要搜索的子節點是一個div ...
所以,你的代碼將是這樣的:
解決方案:
查找有 「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
語法:-)
我希望你有得到你的答案...
但不是'$(this).find('somediv')。css(...)'比第一個慢? – 2011-04-18 06:14:00
@experimentX看到我最新的答案。根據jQuery文檔,他們是等效的:) – 2011-04-18 06:16:06
嗯,...我想那麼。 – 2011-04-18 06:17:22