如何获取jQuery中最接近的上一个元素? [英] How to get the closest previous element in 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');
遍历到最接近的.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屋!