问题描述
是否有类似于jQuery
.closest()
的功能,但用于遍历后代并仅返回最接近的后代?
Is there a function similar to jQuery
.closest()
but for traversing descendants and returning only closest ones?
我知道有.find()
函数,但是它返回所有可能的匹配,而不是最接近的匹配.
I know that there is .find()
function, but it returns all possible matches, not closest.
以下是最接近的的定义(至少对我而言):
首先遍历所有孩子,然后遍历每个孩子.
In first place all childrens are traversed, then each individuals childrens are traversed.
在下面的示例中,id='2'
是id="find-my-closest-descendant"
的最接近的.closest
后代
In example given below id='2'
is closest .closest
descendants of id="find-my-closest-descendant"
<div id="find-my-closest-descendant">
<div>
<div class="closest" Id='1'></div>
</div>
<div class="closest" Id='2'></div>
</div>
请参见 JSfiddle链接.
推荐答案
根据您对closest
的定义,我编写了以下插件:
According to your definition of closest
, I've written the following plugin:
(function($) {
$.fn.closest_descendent = function(filter) {
var $found = $(),
$currentSet = this; // Current place
while ($currentSet.length) {
$found = $currentSet.filter(filter);
if ($found.length) break; // At least one match: break loop
// Get all children of the current set
$currentSet = $currentSet.children();
}
return $found.first(); // Return first match of the collection
}
})(jQuery);
这篇关于与jQuery .closest()类似,但是遍历后代吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!