问题描述
有没有一种便宜的方法来选择元素最深的子元素?
例子:
<div id="SearchHere"><div></div></div></div><div></div><div id="selectThis"></div></div></div></div><div></div></div></div> 解决方案 这可能是比我原来的答案更好的方法:
示例: http://jsfiddle.net/patrick_dw/xN6d5/5/
var $target = $('#SearchHere').children(),$下一个 = $目标;而($next.length){$目标 = $下一个;$next = $next.children();}警报($target.attr('id'));
或者这个更短一点:
示例: http://jsfiddle.net/patrick_dw/xN6d5/6/
var $target = $('#SearchHere').children();而($target.length){$target = $target.children();}警报($target.end().attr('id'));//你需要 .end() 才能到达最后一个匹配的集合
原答案:
这似乎可行:
示例: http://jsfiddle.net/xN6d5/4/一个>
var 级别 = 0;var 最深;$('#SearchHere').find('*').each(function() {if( !this.firstChild || this.firstChild.nodeType !== 1 ) {var levelsFromThis = $(this).parentsUntil('#SearchHere').length;如果(levelsFromThis > 级别){级别 = 级别FromThis;最深=这个;}}});警报(最深的.id);
如果您知道最深的是某个标签(或其他标签),您可以通过将 .find('*')
替换为 .find('div')
例如.
更新为仅在当前元素不 有 firstChild
或者如果有,则 firstChild 是时才检查长度不是类型 1 节点.
Is there a cheap method to select the deepest child of an element ?
Example:
<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>
解决方案 EDIT: This is likely a better approach than my original answer:
Example: 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') );
or this which is even a little shorter:
Example: 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
Original answer:
This would seem to work:
Example: 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 );
If you know that the deepest will be a certain tag (or something else), you could speed it up by replacing .find('*')
with .find('div')
for example.
EDIT: Updated to only check the length if the current element does not have a firstChild
or if it does, that the firstChild is not a type 1 node.
这篇关于在jQuery中选择最深的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-12 20:01