给定一个 DOM 元素,我如何使用给定的 css 类找到它最近的父元素?
$(".editButton").click(function() {
(magic container selector goes here).addClass("editing");
});
我不想使用很多或 $(...).parent().parent() 因为我不想被绑定到特定的 dom 结构。
这应该工作
$(this).parents('.classYouWant:first').addClass("editing");
$( this ).closest( '.yourselector' )
顾名思义,为this元素找到最近的祖先。
使用.parents(".yourClass")而不是.parent().
您可以使用父选择。eg$(".myclass:parent").something();将找到所有具有类 myclass 的元素。