如何将css类添加到父元素?
我正在尝试做一些相当简单的事情,但我可能错过了一些东西......
我有这样的代码:
var $highlights = $j("div.ab-highlights ul li a");
$highlights.hover(
function () {
$j(this).children().addClass('active');
for (i=0; i < $highlights.length; i++)
{
if ($highlights[i] != this)
{
console.log(i);
($highlights.parent()[i]).addClass('lowOpacity');
}
}
},
function () {
$j(this).children().removeClass('active');
}
);
底线是我正在尝试将一个类(“lowOpacity”)附加到除我滚动的元素之外的所有元素。问题是它行不通。不起作用的线路是
($highlights.parent()[i]).addClass('lowOpacity');
我缺少什么?
I am trying to do something rather simple but I am probably missing something...
I have this code:
var $highlights = $j("div.ab-highlights ul li a");
$highlights.hover(
function () {
$j(this).children().addClass('active');
for (i=0; i < $highlights.length; i++)
{
if ($highlights[i] != this)
{
console.log(i);
($highlights.parent()[i]).addClass('lowOpacity');
}
}
},
function () {
$j(this).children().removeClass('active');
}
);
The bottom line is that I am trying attach a class ("lowOpacity") to all elements except the one that I am rolling over. the thing is it won't work. the line that is not working is
($highlights.parent()[i]).addClass('lowOpacity');
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个元素只能有一个父元素。
此代码将向每个突出显示元素的父级添加一个类。
您还可以像这样重构代码:
An element can have only one parent.
This code would add a class to the parent of each highlight element.
You could also refactor your code like this:
看来您想将该类添加到
$highlights
元素的所有父级,期望当前悬停的元素:这行代码替换了整个
for循环。
参考:
不
我想你也有再次从元素中删除
lowOpacity
。您可以将代码简化为:解释为什么您的代码不起作用:
返回一个 DOM 元素,但
addClass
是一个 jQuery 方法。因此,您必须再次将其传递给 jQuery 或使用eq
[docs] 相反:它所做的是获取
$highlights
中元素的所有父元素,然后选择i
第一个。另一种方法是首先选择 $highlights 中的第 i 个元素,然后选择其父元素。
但正如您在上面所看到的,它要容易得多,而且您根本不必循环。
It seems you want to add the class to all parents of the
$highlights
elements, expect the currently hovered one:This line of code replaces the whole
for
loop.Reference:
not
I think you also have to remove the
lowOpacity
from the elements again. You could reduce your code to this:Explanation for why your code does not work:
returns a DOM element, but
addClass
is a jQuery method. Thus you would have to pass it to jQuery again or useeq
[docs] instead:What this is doing is getting all parent elements of the elements in
$highlights
and then selecting thei
th one.Another way would be to first select the
i
th element in$highlights
and then its parent.But as you have seen above, it is much more easier and you don't have to loop at all.
这选择直接父级
选择父级中的多个元素
this selects immediate parent
select multiple elements in parent