[英]jQuery detecting non-existent element
我有一个函数检查img标签是否在一个带有“colorbox”类的figure元素内,如果是,则为一些元素添加一些额外的样式。 但是,即使彩盒图中没有图像,该功能仍然可以运行,我不知道为什么。
我的jQuery看起来像这样
jQuery(document).ready(function($){
if ($(".colorbox").has("img")) {
~code here~
}
}
这里是彩盒图,显然没有img元素......
<figure class="colorbox">
<ficaption>
<h2></h2>
<p></p>
<p></p>
</figcaption>
</figure>
那么为什么jQuery会选择一个不存在的元素呢?
我更喜欢find
功能
var $img = $(".colorbox").find("img");
if ($img.length) { //exisst
}
我会这样做:
jQuery(document).ready(function($){
$('.colorbox img').each(function(){
var imageElement = $(this);
// do whatever you want with this element !
});
// OR this way
$('.colorbox').each(function(){
var box = $(this);
if( box.find('img').length ){
// this means the parent colorBox has at least 1 img-Element
}
});
}
现在你的问题:
$(".colorbox").has("images");
$(".colorbox")
返回元素列表 (如果有)
然后你问列表.has("img")
? 这意味着如果列表中的一个元素内部有一个img元素,那么由于该if语句而得到一个true ,这就是为什么你的代码不能按预期工作的原因
已返回新的jquery子集。 你想要if($(".colorbox").has("img").length)
检查那里是否有任何img标签
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.