我有一个函数可以检查 img 标签是否在具有“colorbox”类的图形元素内部,如果是,则为某些元素添加一些额外的样式。然而,即使颜色框图中没有图像,该功能仍然运行,我不知道为什么。
我的 jQuery 看起来像这样
jQuery(document).ready(function($){
if ($(".colorbox").has("img")) {
~code here~
}
}
这是 colorbox 图,显然没有 img 元素...
<figure class="colorbox">
<ficaption>
<h2></h2>
<p></p>
<p></p>
</figcaption>
</figure>
那么为什么 jQuery 会选择一个不存在的元素呢?
最佳答案
我更喜欢find
函数
var $img = $(".colorbox").find("img");
if ($img.length) { //exisst
}
关于javascript - jQuery 检测不存在的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39007117/