【发布时间】:2011-08-07 15:12:20
【问题描述】:
我正在遍历 jQuery 中的一系列元素(有意地)。
所以基本上我想要这样的东西,但语法正确:
$(".sonicrow").each(function() {
$(this + 'somediv').css('background-color', 'red');
});
显然这是某种对象/字符串混搭。访问 this 对象中的特定 somediv 的正确语法是什么?
谢谢, 约翰。
【问题讨论】:
我正在遍历 jQuery 中的一系列元素(有意地)。
所以基本上我想要这样的东西,但语法正确:
$(".sonicrow").each(function() {
$(this + 'somediv').css('background-color', 'red');
});
显然这是某种对象/字符串混搭。访问 this 对象中的特定 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)实现的。
【讨论】:
$(this).find('somediv').css(...)不是比第一个慢吗??
试试这个:
$(".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');
});
附:我在这里使用了 $(this) 因为 $(".sonicrow") 返回了一个对象,并且您正在遍历该特定对象,因此您必须使用 "this" variable 指向该元素。
另一方面,您使用的是 Jquery,因此 $(this) 为您提供了一个 jquery 对象来执行此操作,否则您必须使用基本的 javascript 语法,例如:this.style.css.property=value 语法:-)
希望你能得到答案...
【讨论】: