如何检查jQuery查找返回true还是false?

Sad*_*san 33 javascript jquery

HTML代码

<div class="parent1">
    <div class="child1">Child1</div>
    <div class="child2">Child2</div>
    <div class="child3">Child3</div>
</div>

<div class="parent2">
    <div class="child1">Child1</div>
    <div class="child2">Child2</div>
</div>
Run Code Online (Sandbox Code Playgroud)

jQuery代码

alert($(".parent1").find(".child3").text());
alert($(".parent2").find(".child3").text());
Run Code Online (Sandbox Code Playgroud)

我的问题是如何检查find函数返回true还是false?

在上面的代码中它返回空白值,其中parent1类具有child3parent2没有child3类的类.

JS小提琴

Ami*_*oki 33

你不能只使用findif状态.您可以使用has或检查length酒店.

var elm = $('.parent1');
if(elm.has('.child3')){
   var child3 = elm.find('.child3');
}
Run Code Online (Sandbox Code Playgroud)

或者就是这样

var child3 = $('.parent1').find(".child3");
if(child3.length > 0) {
  // child3 is present
}
Run Code Online (Sandbox Code Playgroud)

  • 根据文档(https://api.jquery.com/has/),'has'方法返回jQuery,而不是布尔值.这意味着此答案中的第一个示例将始终返回true.使用文档页面上的示例,您需要检查返回对象的length属性是否大于零,而不仅仅是返回了某些内容. (4认同)

Sat*_*pal 7

您可以使用.lengthproperty来检查该元素是否存在.

var elem = $(".parent2").find(".child3");
if(elem.length){
    alert(elem.text());
}else{
    alert('Element doesnt exists')
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用 .has()

var elem = $(".parent2");
if(elem.has(".child3")){
    alert(elem.find(".child3").text());
}else{
    alert('Element doesnt exists')
}
Run Code Online (Sandbox Code Playgroud)


cha*_*tfl 5

每当你在$()其中包装一个选择器时,它总会返回一个包含匹配元素数组的jQuery对象.

因此,您可以使用该length属性来测试是否存在匹配项

var $collection = $(".parent2").find(".child3").length;
if ($collection.length)....
Run Code Online (Sandbox Code Playgroud)

您也可以使用其他方法 is()

var #collection = $(".parent2");
if($collection.children().is(".child3") /* returns tru if there are matches
Run Code Online (Sandbox Code Playgroud)


chr*_*rki 5

作为解释的文档find()find()返回一个 jQuery 对象。它有一个长度属性,可以检查查询是否成功。

if($(".parent1").find(".child3").length > 0) {
    alert("parent1 child3");
}
if($(".parent2").find(".child3").length > 0) {
    alert("parent2 child3");
}
Run Code Online (Sandbox Code Playgroud)