jQuery 找出元素是否是另一个元素的后代的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1059459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:31:40  来源:igfitidea点击:

Best way to find out if element is a descendant of another

jquery

提问by 29er

I am in the process of implementing jQuery, and taking out Prototype libraries in my codebase, and I am wondering if you could give me the best way to implement this functionality in jQuery. I am familiar with the jQuery ancestor>descendant syntax, but just want to check if an element is a descendant by true of false, like the code below: can someone give me the most efficient jQuery solution for this ?

我正在实现 jQuery,并在我的代码库中取出 Prototype 库,我想知道您是否可以给我在 jQuery 中实现此功能的最佳方法。我熟悉 jQuery 祖先>后代语法,但只想通过 true 或 false 检查元素是否是后代,如下面的代码:有人可以为此提供最有效的 jQuery 解决方案吗?

<div id="australopithecus">
  <div id="homo-herectus">
    <div id="homo-sapiens"></div>
  </div>
</div>

$('homo-sapiens').descendantOf('australopithecus');
// -> true

$('homo-herectus').descendantOf('homo-sapiens');
// -> false

采纳答案by Brian Arnold Sinclair

I would think you could take advantage of CSS style selection here, with returned length..

我认为你可以在这里利用 CSS 样式选择,返回长度..

$('#australopithecus #homo-sapiens').length // Should be 1
$('#homo-sapiens #homo-herectus').length // Should be 0

Not exactly true/false, but checking 0/1 as a boolean should work. :)

不完全正确/错误,但检查 0/1 作为布尔值应该有效。:)

Alternately, you could do something like $('#parent').find('#child') and check the length there.

或者,您可以执行类似 $('#parent').find('#child') 的操作并检查那里的长度。

回答by Nathaniel

In jQuery 1.6, you can use the following code generically, e.g. targetElt and parentElt can both be DOM elements or jQuery-wrapped objects, as well as selectors:

在 jQuery 1.6 中,您可以通用地使用以下代码,例如 targetElt 和 parentElt 都可以是 DOM 元素或 jQuery 包装的对象,也可以是选择器:

$(targetElt).closest(parentElt).length > 0

Some of the other answers require you to refer to elements by their IDs, which isn't useful if all you have is a DOM element without an ID. Also, if you want to make sure that the targetElt is a strict descendant of parentElt (in other words, you don't want to count parentElt as its own descendant), make sure to add a targetElt != parentEltcheck before your call to .closest(), or use .parents().find()as Jonathan Sampson suggests.

其他一些答案要求您通过 ID 引用元素,如果您拥有的只是一个没有 ID 的 DOM 元素,这将没有用。此外,如果您想确保 targetElt 是 parentElt 的严格后代(换句话说,您不想将 parentElt 视为其自己的后代),请确保targetElt != parentElt在调用 之前添加检查.closest(),或.parents().find()用作乔纳森·桑普森建议。

回答by TLindig

JQuery

查询

With jQuery >=1.4 (2010) you can use the very fast function jQuery.contains()

使用 jQuery >=1.4 (2010) 你可以使用非常快的函数jQuery.contains()

This static method works with DOM elements, not with jQuery elements and returns trueor false.

此静态方法适用于 DOM 元素,而不适用于 jQuery 元素并返回truefalse.

jQuery.contains( container, descendant )

Example: To check if a element is in the document you could do this:

示例:要检查元素是否在文档中,您可以执行以下操作:

jQuery.contains( document.body, myElement )

Native DOM

原生 DOM

There is also a native DOM method Node.contains()that all browsers since ie5+ supports. So you can do it without jQuery:

还有一个原生 DOM 方法Node.contains(),自 ie5+ 以来的所有浏览器都支持。所以你可以在没有 jQuery 的情况下做到:

document.body.contains( myElement )

回答by Matthew Groves

How about

怎么样


$("#homo-herectus").parents().is("#australopithecus");

回答by John Kugelman

You can use the is()function like so:

您可以is()像这样使用该函数:

alert($('#homo-sapiens').is('#australopithecus *'));
// -> true

alert($('#homo-herectus').is('#homo-sapiens *'));
// -> false

回答by Hongli

$.fn.descendantOf = function(element) {
    element = $(element)[0];
    var current = this;
    var body    = document.body;
    while (current && current != element && current != document.body) {
        current = $(current).parent()[0];
    }
    if (typeof(current) == "undefined" || typeof(current) == "null") {
        return false;
    } else if (current == element) {
        return true;
    } else if (current == document.body) {
        return false;
    }
}

Example:

例子:

<div id="foo">
    <div id="bar">
        <div id="baz"></div>
    </div>
</div>

And:

和:

$('#foo').descendantOf('#bar');  // false
$('#foo').descendantOf('#foo');  // false
$('#foo').descendantOf(document.body);  // true
$('#bar').descendantOf('#foo');  // true
$('#baz').descendantOf('#foo');  // true

回答by Sampson

You could attempt to .find()it in the Elements .children()

你可以.find()在 Elements 中尝试它.children()

$("#lucy").find("#homo-erectus").length;

Or the opposite direction:

或者相反的方向:

$("#homo-erectus").parents().find("#lucy").length;

回答by Serj Sagan

Best method that I found is using Dan G. Switzer, II's method found here: http://blog.pengoworks.com/index.cfm/2008/9/24/Using-jQuery-to-determine-if-an-element-is-a-child-of-another-element

我发现的最佳方法是使用 Dan G. Switzer,在此处找到 II 的方法:http: //blog.pengoworks.com/index.cfm/2008/9/24/Using-jQuery-to-determine-if-an-element -is-a-child-of-another-element

jQuery.fn.isChildOf = function(b){ 
    return (this.parents(b).length > 0); 
};

Then you would just use the plugin as:

然后您只需将插件用作:

$('homo-sapiens').isChildOf('australopithecus');
// -> true

$('homo-herectus').isChildOf('homo-sapiens');
// -> false

回答by Ian Bytchek

An alternative to closest() that uses (almost) the same traverse principle and doesn't include the element itself: child.parentsUntil(ancestor).last().parent().is(ancestor).

使用(几乎)相同的遍历原理并且不包括元素本身的最接近()的替代方法:child.parentsUntil(ancestor).last().parent().is(ancestor)

var child = $('#homo-sapiens');
var ancestor = $('#australopithecus');

console.log(child.parentsUntil(ancestor).last().parent().is(ancestor)); // true

回答by tanathos

Supposing to rewrite your initial statement in:

假设将您的初始语句改写为:

$('#homo-sapiens').descendantOf('#australopithecus');

try to plugin:

尝试插件:

(function($) {
    $.fn.descendantOf = function(parentId) {
        return this.closest(parentId).length != 0;
    }
})(jQuery)