我正在迭代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