如何使用jQuery next()按类选择下一个div [英] How to use jquery next() to select next div by class

查看:91
本文介绍了如何使用jQuery next()按类选择下一个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对jquery还是陌生的,正在为应该相当简单的东西而苦苦挣扎.我想从"MenuItemSelected"类的div中选择"MenuItem"类的上一个和下一个div.

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".

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 -->

这是我认为应该工作的下一个jQuery.

Here is the jquery for next that I thought should have worked.

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

我也尝试过

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

我唯一可以工作的是

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

这似乎是骗人的,有什么主意吗?

That seems hokey, any ideas?

推荐答案

您是否尝试过:

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

我认为您面临的问题是next返回下一个兄弟姐妹,而nextAll返回匹配选择器的所有后续兄弟姐妹的集合.将 :first 选择器应用于nextAll过滤器应该可以解决问题.

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.

我想指出的是,如果标记的结构是一致的(因此始终保证它可以正常工作),那么您当前的解决方案可能(基准,基准,基准)就可以了.更快的方法:

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();

这篇关于如何使用jQuery next()按类选择下一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆