找出元素是否为另一个元素的后代的最佳方法 [英] Best way to find out if element is a descendant of another

查看:88
本文介绍了找出元素是否为另一个元素的后代的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现jQuery,并在我的代码库中删除Prototype库,我想知道是否可以给我最好的方法来在jQuery中实现此功能. 我熟悉jQuery ancestor > descendant语法,但是只想检查一个元素是否是true或false的后代,例如下面的代码: 有人可以为此给我最有效的jQuery解决方案吗?

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 ?

<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

推荐答案

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

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

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

并非完全正确/错误,但是将0/1作为布尔值进行检查应该可以. :)

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

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

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

这篇关于找出元素是否为另一个元素的后代的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆