如何使用jquery选择父元素的同级? [英] How do I use jquery to select a sibling of the parent element?

查看:47
本文介绍了如何使用jquery选择父元素的同级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jquery来专门选择具有相同元素的同级父元素.代码是这样的:

I am trying to use jquery to specifically select a sibling a parent element that has the same . the code is like this:

HTML

    <div class="cool-check-list">
        <ul>
        <li>
            <label>
                <span class="icon"></span> <!-- trying to select this -->
                Awesome Label Name
            </label>

            <ul>
                <li>
                    <label>
                        <span class="icon"></span> <!-- clicking this toggles the class of the above icon class -->
                        Awesome Label Name 2
                    </label>    
                </li>                        
            </ul>
        </li>
        </ul>
   </div>

JQUERY

    $('.icon', '.cool-check-list').click( function(e){

    $(this).parent('li label .icon').toggleClass('icon-alternate');

    });

推荐答案

假设您已经获得了对单击范围的引用,则可以执行以下操作:

Assuming you've already gotten a reference to the clicked span, you could do this:

$(this).closest("ul").siblings().find(".icon")

其中this是您单击的span. closest获取与选择器匹配的最接近的祖先.

Where this is the span you clicked. closest gets the nearest ancestor that matches the selector.

这篇关于如何使用jquery选择父元素的同级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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