如何使用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.