我的 HTML 如下。我需要的是,当有人单击 span 元素时,我想找到其父元素检查一些条件。我使用了 prev() 方法,但它只给了我近父级(这里是parent2)
<div class="container">
<div class="contain">
<div id="parent1">
<div class="parent2">
<span> Click here</span>
</div>
</div>
</div>
</div>
var currentComponent = $(event.target).prev();//这里我得到了parent2
我怎样才能找到父元素(在本例中为parent2)。我对 jquery 不太熟悉,因此我们将不胜感激。
最佳答案
您可以尝试.closest .
来自文档:
the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements. (...) get the first element that matches the selector by testing the element itself and .
它向上遍历 DOM 中的元素祖先,并返回与作为参数传递的选择器
匹配的第一个。因此,在您的示例中,您可以执行类似的操作:
$("span").on("click", function(e) {
var myParent = $(this).closest(".parent2");
var parentOfMyParent = $(this).closest(".parent1");
var contain = $(this).closest(".contain");
var containerAbove = $(this).closest(".container");
});
关于javascript - 使用jquery查找父级父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41756549/