是否存在类似jQuery .closest()但是遍历后代并仅返回最接近的函数的函数?
我知道有.find()功能,但它返回所有可能的匹配,而不是最接近.
编辑:
这是最接近的定义(至少对我而言):
首先,遍历所有儿童,然后遍历每个儿童.
在下面给出的例子中id='2'是最接近的.closest后代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>
Run Code Online (Sandbox Code Playgroud)
请参阅JSfiddle链接.
Jam*_*mes 112
如果"最接近"的后代意味着第一个孩子,那么你可以这样做:
$('#foo').find(':first');
Run Code Online (Sandbox Code Playgroud)
要么:
$('#foo').children().first();
Run Code Online (Sandbox Code Playgroud)
或者,要查找特定元素的第一个匹配项,您可以执行以下操作:
$('#foo').find('.whatever').first();
Run Code Online (Sandbox Code Playgroud)
要么:
$('#foo').find('.whatever:first');
Run Code Online (Sandbox Code Playgroud)
但实际上,我们需要对"最接近的后代"的含义有一个明确的定义.
例如
<div id="foo">
<p>
<span></span>
</p>
<span></span>
</div>
Run Code Online (Sandbox Code Playgroud)
哪<span>会$('#foo').closestDescendent('span')回来?
Rob*_*b W 43
根据你的定义closest,我写了以下插件:
(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);
Run Code Online (Sandbox Code Playgroud)
Fis*_*rdo 18
您可以使用find与:first选择:
$('#parent').find('p:first');
Run Code Online (Sandbox Code Playgroud)
上面的行将找到<p>后代中的第一个元素#parent.
| 归档时间: |
|
| 查看次数: |
76261 次 |
| 最近记录: |