在jQuery中选择最深的孩子
是否有一种吱吱的方法来选择元素的最深的孩子?在jQuery中选择最深的孩子
例子:
<div id="SearchHere">
<div>
<div>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<div>
<div id="selectThis"></div>
</div>
</div>
</div>
<div>
<div></div>
</div>
</div>
编辑:这可能是比我原来的答复更好的方法:
例子:http://jsfiddle.net/patrick_dw/xN6d5/5/
var $target = $('#SearchHere').children(),
$next = $target;
while($next.length) {
$target = $next;
$next = $next.children();
}
alert($target.attr('id'));
或这是连短一点:
例子:http://jsfiddle.net/patrick_dw/xN6d5/6/
var $target = $('#SearchHere').children();
while($target.length) {
$target = $target.children();
}
alert($target.end().attr('id')); // You need .end() to get to the last matched set
原来的答复:
这似乎工作:
例子:http://jsfiddle.net/xN6d5/4/
var levels = 0;
var deepest;
$('#SearchHere').find('*').each(function() {
if(!this.firstChild || this.firstChild.nodeType !== 1 ) {
var levelsFromThis = $(this).parentsUntil('#SearchHere').length;
if(levelsFromThis > levels) {
levels = levelsFromThis;
deepest = this;
}
}
});
alert(deepest.id);
如果您知道最深处将是某个标记(或其他标记),则可以通过将.find('*')
替换为.find('div')
来加速它。
编辑:更新以只检查长度如果当前元素确实不具有firstChild
或如果这样做,该则firstChild不是一个类型1节点。
太棒了!完美的作品!我也将其封装在一个jQuery插件中。这里:https://gist.github.com/714851 – Jonathan 2010-11-25 03:28:24
@jonathanconway - 更新我的答案,可能是更有效的版本。 – user113716 2010-11-25 12:23:34
@ user113716我做了一个更短的版本http://jsfiddle.net/xN6d5/44/ :) – EaterOfCode 2013-01-21 15:24:45
我不认为你可以直接做,但你可以尝试
var s = "#SearchHere";
while($(s + " >div ").size() > 0)
s += " > div";
alert($(s).attr('id'));
这里有答案略有改善,从@ user113716,这个版本的处理时,有没有孩子的情况下,返回目标本身。
(function($) {
$.fn.deepestChild = function() {
if ($(this).children().length==0)
return $(this);
var $target = $(this).children(),
$next = $target;
while($next.length) {
$target = $next;
$next = $next.children();
}
return $target;
};
}(jQuery));
+1,因为我只需要复制/过去以得到我需要的东西,获得嵌套对象或只是初始对象。谢谢! – Georgio 2016-10-03 18:08:11
这个可链接的单线程为我工作,但它假定在下面的层次结构中只有一个叶节点。
jQuery("#searchBeginsHere")
.filter(function(i,e){ return jQuery(e).children().size() === 0; })
每个叶子最深的版本。
http://jsfiddle.net/ncppk0zw/14/
var found = $('#SearchHere *');
for (var i = 0; i < found.length; i++) {
if (i > 1) {
if (found[i].parentNode !== found[i-1]) {
// Deepest. Next element is other leaf
console.log(found[i-1]);
continue;
}
if (i == found.length-1) {
// Deepest. Last element in DOM tree
console.log(found[i]);
}
}
}
并不意味着作为一个批评,但我对你为什么会想着迷? – 2010-09-24 14:26:50
对于所有那些通过搜索引擎发现的人来说,我从乔纳森的patrick dw的改进版本中更新了主旨。还扩大了一点点的指示。你可以在这里找到它:[jQuery最深的插件要点](https://gist.github.com/1014671“jQuery最深的插件要点”) – 2011-06-08 15:54:54