如何使用 jquery next() 按类选择下一个 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1743454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use jquery next() to select next div by class
提问by Ryan Sampson
I'm fairly new to jquery and struggling with something that should be fairly simple. I want to select the previous and next div with class "MenuItem" from the div with class "MenuItemSelected".
我对 jquery 还很陌生,并且正在为一些应该相当简单的事情而苦苦挣扎。我想从类“MenuItemSelected”的 div 中选择类“MenuItem”的上一个和下一个 div。
HTML
HTML
<div id="MenuContainer" class="MenuContainer">
<div id="MainMenu" class="MainMenu">
<div class="MenuItem">
<div class="MenuItemText">Menu Item #1</div>
<div class="MenuItemImage">images/test1.jpg</div>
</div>
<div class="MenuDividerContainer">
<div class="MenuDivider"></div>
</div>
<div class="MenuItem MenuItemSelected">
<div class="MenuItemText">Menu Item #2</div>
<div class="MenuItemImage">images/test2.jpg</div>
</div>
<div class="MenuDividerContainer">
<div class="MenuDivider"></div>
</div>
<div class="MenuItem">
<div class="MenuItemText">Menu Item #3</div>
<div class="MenuItemImage">images/test3.jpg</div>
</div>
</div><!--/ .MainMenu -->
</div><!--/ .MenuContainer -->
Here is the jquery for next that I thought should have worked.
这是我认为应该工作的 next 的 jquery。
$('div.MenuItemSelected').next('.MenuItem');
I also tried
我也试过
$('div.MenuItemSelected').nextAll('.MenuItem');
The only thing i could get to work is
我唯一能上班的就是
$('div.MenuItemSelected').next().next();
That seems hokey, any ideas?
这似乎很糟糕,有什么想法吗?
回答by karim79
Have you tried:
你有没有尝试过:
$('div.MenuItemSelected').nextAll('.MenuItem:first');
I think the problem you are facing is that next
returns the very next sibling, whereas nextAll
returns a collection of all the subsequent siblings matching your selector. Applying the :first
selector to your nextAll
filter should make things right.
我认为您面临的问题是next
返回下一个兄弟姐妹,而nextAll
返回与您的选择器匹配的所有后续兄弟姐妹的集合。将:first
选择器应用于您的nextAll
过滤器应该会使事情正确。
I would like to point out, that if the structure of your markup is consistent (so it's always guaranteed to work), then your current solution might(benchmark, benchmark, benchmark) well be the faster way:
我想指出的是,如果您的标记结构是一致的(因此它始终保证有效),那么您当前的解决方案可能(基准、基准、基准)可能是更快的方法:
$('div.MenuItemSelected').next().next();
回答by Achilles
Have you tried: .parent() and .children() ? http://docs.jquery.com/Traversing
你试过: .parent() 和 .children() 吗?http://docs.jquery.com/Traversing