在完整文档中查找最接近的元素 [英] Find closest element in complete document
问题描述
我已经使用Jquery index
为我的文档建立了索引,给定了一定的索引值,我想用一些class
'定位''nearest'元素.这对我不起作用:
I have indexed my document using Jquery index
Given a certain index value, I would like to 'locate' the 'nearest' element with some class
. This will not work for me:
$(variableIndexNumber).closest('.class');
原因是有时.class
会更改其位置,这意味着它可以在文档中的任何位置.有时是兄弟姐妹,有时是父母,有时在文档中或在底部.因此,通常的选择器next
closest
first
nextAll
等对我不起作用(由于文档树)
The reason is that sometimes the .class
changes its position, meaning it could be anywhere in the document. Sometimes its a sibling, sometimes a parent, sometimes way up in document or in the bottom. So the usual selctors next
closest
first
nextAll
etc don't work for me (because of document tree)
我该如何尝试获取相对于某些其他元素(由变量给定)最接近的.class
?
What can I try to get the nearest .class
relative to some other element (given by variable)?
推荐答案
使用.prevUntil('.class')
,.nextUntil('.class')
,.parentsUntil('.class')
,然后比较它们的大小.
Use .prevUntil('.class')
, .nextUntil('.class')
, .parentsUntil('.class')
, then compare their sizes.
就DOM结构而言,尺寸最小的那个元素是最接近元素的.
Whichever one has the least size is the closest to the element in terms of DOM structure.
更新:在此过程中,您还将需要.andSelf()
,.filter()
和典型的.next()
和.prev()
才能真正达到所需的目标.演示已更新.您可以看到现在的代码更加通用.
UPDATE: In the process, you will also need .andSelf()
, .filter()
and typical .next()
and .prev()
to actually get to the target you want. Demo has been updated. You can see that now the code is more generic.
您可能还需要排序功能,就像我在下面的概念验证中所做的那样.
You'll probably need a sorting function too, as I've did in the proof-of-concept below.
演示: http://jsfiddle.net/terryyounghk/FzA78/
旁注:没有.childrenUntil()
,因为这是DOM树的向外分支,而不是向文档根的内部分支,以防万一.但是我的猜测是,您可以先执行$('.me').find('.class')
,然后对每个执行.parentsUntil('.me')
,然后比较大小.我不确定这是否行得通.
Side-note: There's no .childrenUntil()
, because that's branching outwards the DOM tree, not inwards towards the document root, in case you're wondering. But my guess is, you could do a $('.me').find('.class')
first, then for each of them, do a .parentsUntil('.me')
instead, then compare the sizes. I'm not sure if this would work though.
这篇关于在完整文档中查找最接近的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!