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

标签 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>

jQuery 代码

alert($(".parent1").find(".child3").text());
alert($(".parent2").find(".child3").text());

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

在上面的代码中,它返回空值,其中 parent1 类有 child3 类,而 parent2 类没有 child3类。

JS Fiddle

最佳答案

您不能在 if 条件中只使用 find。您可以使用 has 或检查 length 属性。

var elm = $('.parent1');
if(elm.has('.child3')){
   var child3 = elm.find('.child3');
}

或者只是这样

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

关于javascript - 如何检查 jQuery 查找返回 true 还是 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27646559/

相关文章:

javascript - 如何用php或js包裹图形纹理?

javascript - 将回调数据分配给变量

php - codeigniter 中的自动完成

javascript - Angularjs 1.3.15 - 在 Promise 返回后更新 $scope

javascript - 如何隔离和迭代 React 应用程序中的各个 React 组件

jQuery 加载不更新 Internet Explorer 中的文档

jquery - 使用 jQuery 拖放 UI 布局

javascript - 在 jQuery + Datatables 中设置 `processData: false` 会将未知内容附加到我的 Ajax 调用的 URL

javascript - 我如何将键插入 js 数组以转换为 json

javascript - 设置单元格值并使其在内联编辑中保持可编辑