如何使用jquery next()按类选择下一个div

我对jquery很新,并且在应该相当简单的事情上挣扎。 我想从类“MenuItemSelected”的div中选择带有“MenuItem”类的上一个和下一个div。

HTML

 

这是我认为应该有效的下一个jquery。

 $('div.MenuItemSelected').next('.MenuItem'); 

我也试过了

 $('div.MenuItemSelected').nextAll('.MenuItem'); 

我唯一可以上class的是

 $('div.MenuItemSelected').next().next(); 

这看起来很好,有什么想法吗?

你有没有尝试过:

 $('div.MenuItemSelected').nextAll('.MenuItem:first'); 

我认为你面临的问题是next返回下一个兄弟nextAll ,而nextAll返回与你的选择器匹配的所有后续兄弟nextAll的集合。 将:first选择器应用于nextAllfilter可以使事情正确。

我想指出,如果你的标记结构是一致的(所以它总能保证工作),那么你当前的解决方案(基准,基准,基准)可能是更快的方式:

 $('div.MenuItemSelected').next().next(); 

你试过:.parent()和.children()? http://docs.jquery.com/Traversing