jQuery-查找具有类名的最接近的父级 [英] Jquery - Find the closest parent having a class name
问题描述
在我的应用程序中,我想找到一个具有类名的单击元素的最接近的父级.为此,我使用最接近方法使用以下代码.我知道它具有使用选择器获取最接近元素的功能.但是在这里,我给了一个类名作为选择器之类;
In my application i want to find the closest parent, of a clicked element, having a class name. For that i have the following code with closest method. I know it has the functionality to get the closest element with a selector. But here i given a class name as selector like;
$(".selectable").click(function(){
var closest = $(this).closest('.selectable');
});
问题是,如果当前元素及其父元素具有相同的类.selectable
,它将返回当前元素本身.但是实际上我想要它的父母.例如,
The problem is if the current element and its parent have the same class .selectable
, it returns the current element itself. But actually i want its parent. For example,
<div class="selectable div-1">
<div class="selectable div-2">
<!--elements here-->
</div>
</div>
在上面的示例中,我单击了.div-2
div,它返回了.div-2
本身,而不是.div-1
div.请不要让我从父级中删除.selectable
类,这是为了功能..:-)
In the above example i clicked on .div-2
div, it returns the .div-2
itself, not the .div-1
div. Please dont ask me to remove .selectable
class from the parent, it's for the functionality.. :-)
推荐答案
要获取特定类的第一个父级:
To get the first one parent of specific class:
$(this).parents('.selectable').first();
这篇关于jQuery-查找具有类名的最接近的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!