jQuery最接近排除自身 [英] jQuery closest exclude self

查看:80
本文介绍了jQuery最接近排除自身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

closest()将通过测试元素本身并在DOM树中遍历其祖先来获得与选择器匹配的第一个元素.但是我想知道是否有任何方法可以得到排除自身的结果(我的意思是仅仅得到它的父母).

closest() will get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. But I want to know if there is any way to get the result excluding itself (I mean just get the parents of it).

让我举个例子.请检查一下.

Let me take a example. Please review it.

<div id='div1' class="container">
    <div id="div2" class="container">
        <!--many nested div.container as it directly or indirectly children -->
    </div>
    <div id="div3" class="container">
        <!--many nested div.container as it directly or indirectly children -->
    </div>
</div>

$(function() {

    $('div.container').on('mouseover', function(e){
        //I only want to select the first parent with the class container.
        //closest include the this element. 
        console.log($(this).closest('.container').attr('id'));
    });
});

推荐答案

正确的答案是.parents('.container:first');谢谢

这篇关于jQuery最接近排除自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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