且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在jQuery中选择最深的孩子

更新时间:2023-01-28 18:49:55

这可能是比我原来的答案更好的方法:

示例: 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.

相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
在jQuery中选择最深的孩子
发送“验证码”获取 | 15天全站免登陆
上一篇 : :在HSV颜色空间(Python,OpenCV,图像分析)中定义组织学图像蒙版的颜色范围:下一篇 : 对OpenCV中的图像应用蒙版?

相关阅读

技术问答最新文章