Jquery检查父项是否有ID

Ale*_*org 9 jquery

嗨,我正在尝试检查父元素是否包含ID

这是我的清单

<ul>
<li></li>
<li id="selected">
    <ul>
        <li></li>
        <li></li>
    </ul>
</li>
<li></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

不知道如何在这里制作正确的清单?

if (jQuery(LiElement).parent("#selected"))
{
    //If parent has id=selected
}
else
{
    //If parent dont have id=selected
}
Run Code Online (Sandbox Code Playgroud)

有谁可以帮助我吗?

use*_*716 20

你可以测试以下length属性.parent("#selected"):

if( Query(LiElement).parent("#selected").length ) 
Run Code Online (Sandbox Code Playgroud)

如果父项具有#selectedID,则返回1(true),否则返回0(false).

请注意,您仅测试直接父级.我想这就是你想要的.

如果ID不是直接父级,则可以使用closest()测试ID的任何祖先.

if( Query(LiElement).closest("#selected").length ) 
Run Code Online (Sandbox Code Playgroud)

请注意,这也将测试当前元素.


Squ*_*kle 0

不积极,但我认为应该是这样

if ($('li').parents('#selected')) {...} else {...}
Run Code Online (Sandbox Code Playgroud)

  • 您需要测试 .length; .parents() 将始终返回一个 jQuery 对象(即使没有任何匹配),该对象的计算结果为 true (3认同)