使用 jQuery next() 并忽略嵌套列表?
我在这里遇到一个小问题,我想使用 next() 但我想忽略嵌套列表...这该怎么办?现在接下来将选择主列表和嵌套列表。
所以说我有......
<ul id="mainlist">
<li>1</li>
<li class="selected">2</li>
<ul id="nested">
<li>A</li>
<li>B</li>
<li>B</li>
</ul>
<li>3</li>
</ul>
$(".selected").next().css("color", "red");
在这种情况下,整个“嵌套”列表颜色变为红色。但我希望“3”是红色的......在这种情况下我能做什么?
如有任何帮助,我们将不胜感激,谢谢。
注意:这只是一个示例问题,我实际上正在尝试通过列表项创建导航,但认为此代码对于示例来说会更容易。
I'm having a little problem here, I want to use next() but I want to ignore nested lists... how can this be done? Right now next will select both the main list and the nested lists.
So say I have...
<ul id="mainlist">
<li>1</li>
<li class="selected">2</li>
<ul id="nested">
<li>A</li>
<li>B</li>
<li>B</li>
</ul>
<li>3</li>
</ul>
$(".selected").next().css("color", "red");
In this situation, the entire "nested" list color changes to red. But I would like the "3" to be red... What can I do in this situation?
Any help is appreciated, thank you.
NOTE: This is just an example problem, I'm actually trying to create navigation through list items but figured this code would be easier for an example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的问题(导致您的代码无法按预期工作)是
ul
标记实际上并未嵌套在li
标记中。ul
标签是同一级别的li
标签之后的下一个标签。如果您的意思是嵌套,那么您的 HTML 应该如下所示:然后您的代码将按需要工作。你可以在这里看到: http://jsfiddle.net/jfriend00/nfbPp/
如果你真的想说对于 HTML 来说,您只想选择与
.selected
项处于同一级别的下一个li
标记,那么您需要不同的 jQuery,因为.next()
将选择下一个同级,即ul
标记。您需要这样的东西:这将检查以下所有兄弟姐妹并选择与选择器
'li:first'
匹配的兄弟姐妹(这将仅获取第一个li
标记)。您可以在这里看到它的工作: http://jsfiddle.net/jfriend00/QrUtL/
Your issue (causing your code not to work as desired) is that the
ul
tag isn't actually nested in theli
tag. Theul
tag is the next tag after theli
tag at the same level. If you mean for it to be nested, then your HTML should look like this:And, then your code will work as desired. You can see that here: http://jsfiddle.net/jfriend00/nfbPp/
If you actually mean for the HTML to be the way it is and you just want to select the next
li
tag that's at the same level as the.selected
item, then you need different jQuery because.next()
will select the next sibling which is theul
tag. You would need something like this:This will examine all the following siblings and select the ones that match the selector
'li:first'
(which will get just the firstli
tag).which you can see work here: http://jsfiddle.net/jfriend00/QrUtL/
这适用于您的示例。
对于最后一个列表元素
This will work for your example.
For last list element
可能有用,但不确定:),尝试一下
might work, not sure :), try it out
使用
.nextAll()
并过滤到第一个就可以了,即使尽管这可能不是最有效的方法:jsFiddle demo
Using
.nextAll()
and filtering to the first one would work, even though it might not be the most efficient way:jsFiddle demo