11

我一定错过了一些非常重要的东西,我一直在使用 .parent().parent().parent().. 等来遍历 DOM,并使用 .next().next() 来遍历 DOM。

我知道这是错误的,我需要更可靠的东西,我需要一个选择器,它会从单击的元素 $(this) 向下遍历 DOM,以查看单击的元素是否在具有“last”类的元素内。

div.last > div > table > tr > td > a[THE ITEM CLICKED is in the element last]

div > div > table > tr > td > a[THE ITEM CLICKED is not in the element last]

那么如果结果有长度

var isWithinLastRow = [amazingSelector].length;

在这种情况下做其他事情。

4

4 回答 4

22

试试这个:- http://jsfiddle.net/adiioo7/PjSV7/

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:-

jQuery(function($){
    $("a").on("click",function(){
       if($(this).closest(".last").length>0)
       {
           alert("Clicked anchor with div parent class as last");
       }
    });
});
于 2013-06-12T15:09:56.050 回答
7

你的问题有点难以理解。您想检查单击的元素是否具有 class 的祖先元素last,是吗?

如果是这样,您可以这样做$.fn.parents

if ($(this).parents('.last').length) {
    // element has an ancestor element with the class "last"
}
于 2013-06-12T15:05:07.433 回答
3

你可以这样做 -

if($(this).closest(".last").length > 0) {
   alert("it's inside");
}
于 2013-06-12T15:06:11.643 回答
1

您可以使用.closest()

var isWithLastRow = $(this).closest('div.last').length
于 2013-06-12T15:05:21.180 回答