Javascript / Jquery 树遍历问题
假设我有以下
<ul>
<li>Item 1</li>
<li>Item 2
<ul>
<li>Sub Item</li>
</ul>
</li>
<li>Item 3</li>
</ul>
这个列表是由其他一些代码自动生成的(因此添加独占 id/class' 是不可能的。假设我有一些 jquery 代码,指出如果我将鼠标悬停在 li 上,它会获得背景颜色。但是,如果我将鼠标悬停在“子项目”列表项上,“项目 2”也会突出显示,这样如果用户将鼠标悬停在“子项目”上,它只会在其上放置背景颜色,而不是在其上。 “第 2 项”也是如此?
我还忘了提到我已经在页面上有了类似 $("li").doSomething... 的东西...
Suppose I have the following
<ul>
<li>Item 1</li>
<li>Item 2
<ul>
<li>Sub Item</li>
</ul>
</li>
<li>Item 3</li>
</ul>
This list is auto-generated by some other code (so adding exclusive id's/class' is out of the question. Suppose I have some jquery code that states that if I mouseover an li, it gets a background color. However, if I mouseover the "Sub Item" list item, "Item 2" will be highlighted as well. How can I make it so that if the user mouses over "Sub Item" it only puts a background color on that and not on "Item 2" as well?
I also forgot to mention that I already have something like $("li").doSomething... on the page already...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您需要一些 CSS、悬停类和
元素上的背景,以便父级的背景不会显示在子级上(因为否则它们具有透明背景) ,因此父级的任何内容都会显示),如下所示:
然后您可以使用
mouseover
和mouseout
(不是mouseenter
和mouseleave
就像.hover()
使用),如下所示:您可以在此处查看工作演示。这使用
.mouseover()
和.mouseout()
(因此它在进入/离开子元素时触发,其中mouseenter
/mouseleave
特别不会)。悬停时,我们将hover
类应用于当前并从可能拥有该类的任何父类中删除该类。此外,我们还使用
event.stopPropagation()
所以同样的事情不会发生在这个元素的父元素上...只需在演示中注释掉它,看看这会如何影响事物:)First you'll need a bit of CSS, a hover class and a background on the
<li>
elements, so the parent's background doesn't show up on children (because otherwise they have a transparent background, so whatever the parent has will show), like this:Then you can use
mouseover
andmouseout
(notmouseenter
andmouseleave
like.hover()
uses), like this:You can see a working demo here. This uses
.mouseover()
and.mouseout()
(so it fires when entering/leaving a child element, whichmouseenter
/mouseleave
specifically won't). On hover we apply thehover
class to the current<li>
and remove the class from any parents that might have it. Also we prevent the event from bubbling withevent.stopPropagation()
so the same thing doesn't happen on this element's parents...just comment this out in the demo to see how this affects things :)
尝试 $('ul li li') 作为您的选择器。 IE
编辑
对于 JQuery 解决方案,它是相同的选择器。 IE
`$('ul li li').css('背景','#00F');
try $('ul li li') as your selector. IE
EDIT
For a JQuery solution, it's the same selector. IE
`$('ul li li').css('background','#00F');