如何获取jQuery中最接近的上一个元素? [英] How to get the closest previous element in jQuery?

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

问题描述

我想从当前选择的对象标签中获取最接近的对象标签.但是它必须严格地在上面.假设我有ID为A的对象.如何获得最接近的对象标签?在这种情况下,我想获取ID为B的对象标签.每个div容器都可以包含一个对象标签或其他标签.

I want to get the closest object tag from the currently selected object tag. But it has to be strictly above. Suppose I have the object with id A. How can I get the closest object tag above it? In this case I want to get the object tag with id B. Each div container can contain a object tag or something else.

<div class="message">
    <span></span>
</div>
<div class="message">
    <object id="C"></object>
</div>
<div class="message">
    <object id="B"></object>
</div>
<div class="message">
    <span></span>
</div>
<div class="message">
    <object id="A"></object>
</div>
<div class="message">
    <object id="Z"></object>
</div>

推荐答案

假定this是ID为A

$(this).closest('.message').prevUntil('.message:has(object)').prev().find('object');

FIDDLE

遍历到最接近的.message,然后检查先前的元素,直到找到包含object标签的元素,然后停止,但在该标签之前的元素处停止,因此我们调用prev进行查找进一步,然后使用find查找对象标签.

traverses up to the closest .message then checks previous elements until it finds one that contains an object tag, then it stops, but it stops at the element before that tag, so we call prev to go one step further, and then use find to find the object tag.

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

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