jQuery:如果所选元素 $(this) 的父元素的类名为“last”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17068838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: If the selected element $(this) has a parent with a classname of 'last'
提问by Iamsamstimpson
I must be missing something quite important, I have been using .parent().parent().parent().. etc to traverse down the DOM and .next().next() to traverse up the DOM.
我一定遗漏了一些非常重要的东西,我一直在使用 .parent().parent().parent().. 等来遍历 DOM 和 .next().next() 来遍历 DOM。
I know this is wrong and that I need something more reliable, I need a selector that will traverse from the clicked element $(this) down the DOM to see if the element clicked is within an element with a class of "last".
我知道这是错误的,我需要更可靠的东西,我需要一个选择器,它会从单击的元素 $(this) 向下遍历 DOM,以查看单击的元素是否在具有“last”类的元素内。
div.last > div > table > tr > td > a[THE ITEM CLICKED is in the element last]
and
和
div > div > table > tr > td > a[THE ITEM CLICKED is not in the element last]
then if the result has length
那么如果结果有长度
var isWithinLastRow = [amazingSelector].length;
do something else in this case.
在这种情况下做其他事情。
回答by Aditya Singh
Try this out:-http://jsfiddle.net/adiioo7/PjSV7/
试试这个:- http://jsfiddle.net/adiioo7/PjSV7/
HTML:-
HTML:-
<div class="last">
<div>
<table>
<tr>
<td>
<a>Test</a>
</td>
</tr>
</table>
</div>
</div>
<div>
<div>
<table>
<tr>
<td>
<a>Test</a>
</td>
</tr>
</table>
</div>
</div>
JS:-
JS:-
jQuery(function($){
$("a").on("click",function(){
if($(this).closest(".last").length>0)
{
alert("Clicked anchor with div parent class as last");
}
});
});
回答by lonesomeday
Your question is a little hard to understand. You want to check if the element clicked has an ancestor element with the class last, yes?
你的问题有点难以理解。您想检查单击的元素是否具有 class 的祖先元素last,是吗?
If so, you can do so with $.fn.parents:
如果是这样,你可以这样做$.fn.parents:
if ($(this).parents('.last').length) {
// element has an ancestor element with the class "last"
}
回答by Mohammad Adil
You can do this -
你可以这样做 -
if($(this).closest(".last").length > 0) {
alert("it's inside");
}

