我正在检查数据属性,availability
是“是”还是“否”。如果是“否”,我将找到特定的.smallCatalogBlock
,并希望在其上附加.soonOverlay
。
现在,元素没有附加到.smallCatalogBlock
。我有一个console.log检查来查看条件是否成功运行,并且它具有正确数量的找到的元素。html只是没有被追加。
有人知道我做错了什么吗?
$('.smallCatalogBlock').each(function() {
if ($(this).data('availability') === 'No') {
$(this).find('.smallCatalogBlock').append('<div class="soonOverlay"><div class="soonOverlayInner"><div class="total-center"><p class="dGw">Coming Soon</p></div></div></div>');
console.log("It should be working");
}
});
.smallCatalogWrap {
width: 100%;
height: auto;
margin: 60px 0;
}
.smallCatalogBlock {
width: 25%;
height: auto;
display: inline-block;
vertical-align: top;
margin: 20px auto;
text-decoration: none;
}
.smallCatalogBlock img {
width: 80%;
height: auto;
box-shadow: 10px 5px 5px rgba(0,0,0,.3);
display: block;
margin: 0px auto 15px auto;
}
.smallCatalogTitle {
font-family: 'Nunito', sans-serif;
color: #4d4d4d;
font-size: 1.3rem;
text-align: center;
display: block;
font-weight: 400;
}
.comingSoonSmall {
position: relative;
}
.comingSoonSmall .soonOverlay {
width: 80%;
height: 100%;
background: #b82222;
opacity: .8;
position: absolute;
top: 0;
margin: 0 10%;
}
.soonOverlayInner {
position: relative;
min-height: 350px;
}
.soonOverlayInner .dGw {
font-weight: 600;
text-transform: uppercase;
font-size: 2.5rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="smallCatalogWrap">
<div class="smallCatalogBlock" data-availability="Yes">
<span class="smallCatalogTitle">A</span>
<div class="smallCatalogButtonWrap">
<div class="catalogSmallCircle"></div>
</div>
</div><div class="smallCatalogBlock comingSoonSmall" data-availability="No">
<span class="smallCatalogTitle">B</span>
<div class="smallCatalogButtonWrap">
<div class="catalogSmallCircle"></div>
</div>
</div><div class="smallCatalogBlock comingSoonSmall" data-availability="No">
<span class="smallCatalogTitle">C</span>
<div class="smallCatalogButtonWrap">
<div class="catalogSmallCircle"></div>
</div>
</div>
</div>
最佳答案
这是因为当您使用$(this)
时,对象本身就是类.smallCatalogBlock
的项。因此,当您运行$(this).find('.smallCatalogBlock')
时,它会尝试在具有类smallCatalogBlock
的元素中查找具有类smallCatalogBlock
的元素,但失败。既然找不到,就不能追加。如果你只是做$(this).append(...)
,它应该可以工作。