查找最接近的上一个元素jQuery [英] Find closest previous element jQuery

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

问题描述

我想要与此 person 类似的东西,除了要匹配的元素可能不是直接同级.

例如,如果我有此HTML,

<h3>
    <span>
        <b>Whaddup?</b>
    </span>
</h3>
<h3>
    <span>
        <b>Hello</b>
    </span>
</h3>
<div>
    <div>
        <img />
    </div>
     <span id="me"></span>
</div>
<h3>
    <span>
        <b>Goodbye</b>
    </span>
</h3>

我希望能够做这样的事情:

var link = $("#me").closestPreviousElement("h3 span b");
console.log(link.text()); //"Hello"

在jQuery中有简单的方法吗?

编辑:我应该使我的说明更清晰一些. $("#me")可以有也可以没有父div.该代码不应假定它确实如此.我不一定对周围的元素一无所知.

解决方案

var link = $("#me").closest(":has(h3 span b)").find('h3 span b');

示例: http://jsfiddle.net/e27r8/

这使用 closest() [docs] 方法获取具有嵌套h3 span b的第一个祖先,然后执行.find().

当然您可以有多个匹配项.


否则,您正在考虑进行更直接的遍历.

var link = $("#me").closest("h3 + div").prev().find('span b');

此代码与更新的HTML一起使用.

示例: http://jsfiddle.net/e27r8/2/


已更新,可处理更新的问题.

var link = $("#me").closest("h3 + *").prev().find('span b');

这使.closest()的目标元素具有通用性,因此,即使没有父元素,它也仍然可以工作.

示例: http://jsfiddle.net/e27r8/4/

I am wanting something similar to this person, except the element I want to match might not be a direct sibling.

If I had this HTML, for example,

<h3>
    <span>
        <b>Whaddup?</b>
    </span>
</h3>
<h3>
    <span>
        <b>Hello</b>
    </span>
</h3>
<div>
    <div>
        <img />
    </div>
     <span id="me"></span>
</div>
<h3>
    <span>
        <b>Goodbye</b>
    </span>
</h3>

I would want to be able to do something like this:

var link = $("#me").closestPreviousElement("h3 span b");
console.log(link.text()); //"Hello"

Is there an easy way to do this in jQuery?

EDIT: I should have made my specification a little bit clearer. $("#me") may or may not have a parent div. The code should not assume that it does. I don't necessarily know anything about the surrounding elements.

解决方案

var link = $("#me").closest(":has(h3 span b)").find('h3 span b');

Example: http://jsfiddle.net/e27r8/

This uses the closest()[docs] method to get the first ancestor that has a nested h3 span b, then does a .find().

Of course you could have multiple matches.


Otherwise, you're looking at doing a more direct traversal.

var link = $("#me").closest("h3 + div").prev().find('span b');

edit: This one works with your updated HTML.

Example: http://jsfiddle.net/e27r8/2/


EDIT: Updated to deal with updated question.

var link = $("#me").closest("h3 + *").prev().find('span b');

This makes the targeted element for .closest() generic, so that even if there is no parent, it will still work.

Example: http://jsfiddle.net/e27r8/4/

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

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