我正在实现jQuery,并在我的代码库中取出Prototype库,我想知道你是否可以给我在jQuery中实现这个功能的最佳方法.我熟悉jQuery祖先>后代语法,但只想检查一个元素是否是true的后代,如下面的代码:有人能为我提供最有效的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
Run Code Online (Sandbox Code Playgroud)
小智 108
在jQuery 1.6中,您可以使用以下代码,例如targetElt和parentElt都可以是DOM元素或jQuery包装的对象,以及选择器:
$(targetElt).closest(parentElt).length > 0
Run Code Online (Sandbox Code Playgroud)
其他一些答案要求您按ID引用元素,如果您拥有的只是没有ID的DOM元素,则无效.此外,如果您想确保targetElt是parentElt的严格后代(换句话说,您不希望将parentElt计为其自己的后代),请确保targetElt != parentElt在调用之前添加一个检查.closest(),或者.parents().find()用作乔纳森桑普森建议.
TLi*_*dig 44
使用jQuery> = 1.4(2010),你可以使用非常快的函数jQuery.contains()
这个静态方法适用于DOM元素,而不是jQuery元素和返回true或false.
jQuery.contains( container, descendant )
Run Code Online (Sandbox Code Playgroud)
示例:要检查元素是否在文档中,您可以执行以下操作:
jQuery.contains( document.body, myElement )
Run Code Online (Sandbox Code Playgroud)
更新:
还有一个本地DOM方法Node.contains(),所有浏览器都是ie5 +支持的.所以你可以不用jQuery来做到这一点:
document.body.contains( myElement )
Run Code Online (Sandbox Code Playgroud)
Bri*_*air 31
我认为你可以在这里利用CSS样式选择,返回长度..
$('#australopithecus #homo-sapiens').length // Should be 1
$('#homo-sapiens #homo-herectus').length // Should be 0
Run Code Online (Sandbox Code Playgroud)
不完全是真/假,但将0/1作为布尔值检查应该有效.:)
或者,您可以执行类似$('#parent').find('#child')并检查其长度的操作.
Mat*_*ves 21
怎么样
$("#homo-herectus").parents().is("#australopithecus");
Run Code Online (Sandbox Code Playgroud)
你可以使用这样的is()功能:
alert($('#homo-sapiens').is('#australopithecus *'));
// -> true
alert($('#homo-herectus').is('#homo-sapiens *'));
// -> false
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37605 次 |
| 最近记录: |