如何检查jquery obj是否包含另一个jquery obj?

时间:2017-07-02 23:20:12

标签: jquery

如果我有2个jquery对象,如何检查第一个是否包含第二个?

我也不想引用jquery本身,我想使用第一个jquery对象中的方法,比如

<ul>
   <li></li>
</ul>

var obj1 = $("ul");
var obj2 = $("li");
obj1.contains(obj2)   --> true      [contains does not exist, how would I implement it?]

1 个答案:

答案 0 :(得分:0)

为了测试给定的jQuery对象是否包含另一个特定的jQuery对象,请使用以下方法;如果条件满足则返回 true ,否则 false

var obj1 = $( "ul" );
var obj2 = $( "li" );

function checkForChildren( obj1, obj2 ) {
    if ( obj2[0].localName !== undefined && obj1.children( obj2[0].localName ).length > 0 )  {
        console.log( 'true' );
        return true;
    }
    console.log( 'false' );
    return false;
}
checkForChildren( obj1, obj2 );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
    <li></li>
</ul>