检查div是否存在jquery

时间:2018-06-04 13:17:25

标签: jquery

if(.is-open close-now){
jQuery(".extra_div").click(function($){
            alert('"Sorry, this takeaway only accepts orders during its opening hours"');
        });
}

我认为上面的内容是我需要的,但我不知道if语句部分应该如何解决。

我正在查看是否存在某个div,如果存在,请在点击代码上运行以下jQuery。

更新1

if ($(.is-open close-now).length){
jQuery(".extra_div").click(function($){
            alert('"Sorry, this takeaway only accepts orders during its opening hours"');
        });
}

两个div是

开放 - 现在 - 开放 .is-open close-now - 关闭

1 个答案:

答案 0 :(得分:0)

您可以轻松查看其length。如果某个元素不存在,则检查其length将返回false

if($('.is-open').length){
  // exists
  console.log('is-open exists');
  // do stuff
}
if($('.not-is-open').length){
  // doesn't exist
  console.log('not-is-open exists');
  // do stuff
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="is-open">
</div>

相关问题