我有一个函数,检查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会选择一个不存在的元素呢?
解决方法
我会这样做:
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,这就是为什么你的代码不能按预期工作的原因