jQuery查找具有属性的最接近的父链接 [英] jQuery find closest parent link with attribute

查看:111
本文介绍了jQuery查找具有属性的最接近的父链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从子级.startpoint中找到属性为findme的最近链接. 结构:

I'd like to find the closest link with attribute findme from a children .startpoint. Structure:

<ul>
    <li><a href="#">Point one</a></li>
    <li><a href="#" data-findme="yipi">Point one</a>
        <ul>
            <li><a href="#">Hello</a></li>
            <li><a href="#">Hello</a>
                <ul>
                    <li><a href="#" class="startpoint">My Startpoint</a></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

JavaScript(jQuery):

JavaScript (jQuery):

$(document).ready(function(){
    console.log(
        $('.startpoint').closest("*[data-findme]")
    );
});

由于问题是元素data-findme不是父元素,而是元素的另一个子元素,因此我的示例找不到该元素. 示例: http://jsfiddle.net/rjhgvxoe/

Since the problem is, that the element data-findme is not a a parent element instead it is another child of a parent, my example will not find the element. The example: http://jsfiddle.net/rjhgvxoe/

我如何使它工作?

推荐答案

您将需要这样的选择器:

You would need a selector like this:

$('.startpoint').closest("li:has(*[data-findme])")

这将查询最接近的<li>元素,其中包含具有属性data-findme的元素.从那里抢锚

That would query for the closest <li> element which contains an element with the attribute data-findme. To grab the anchor from there

$('.startpoint').closest("li:has(*[data-findme])").children('[data-findme]')

这篇关于jQuery查找具有属性的最接近的父链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆