我正在开发一个网站,我想检查元素中是否有任何内容。
下面是我的 html 代码。我已经提到过条件#1 where opacity-pointseven
如果类应该通过脚本添加类featured-block__title
and featured-block__tag
里面有内容。
<div class="featured-block">
<a href="/" class="featured-block__item cf">
<div class="featured-block__item-inner">
<figure class="featured-block__image img-fit">
<img src=""> // (condition#1, where opacity-pointseven needs to be added)
</figure>
<div class="featured-block__content">
<h1 style="margin-bottom:0px;" class="featured-block__title">Trans Mountain Pipeline: NEB Releases New Report, Recommends Approval </h1>
<h1 class="featured-block__tag"> More Coverage</h1>
</div>
</div>
</a>
</div>
问题陈述:
我尝试了以下方法,但似乎无法正常工作。
<script>
jQuery(function ($) {
if ($(this).find(".featured-block__title").not(":empty") && $(this).find(".featured-block__tag").not(":empty")) {
$(this).find(".img-fit img").addClass("opacity-pointseven"); // For condition#1
}
});
})
</script>
您可以循环父 div 并找到子项,然后在其中添加类。
在这个例子中,我得到$('.featured-block__item-inner')
作为父母,然后找到里面的物品。
$('.featured-block__item-inner').each(function() {
if ($(this).find(".featured-block__title").not(":empty").length > 0 && $(this).find(".featured-block__tag").not(":empty").length > 0) {
$(this).find(".img-fit img").addClass("opacity-pointseven"); // For condition#1
} else {
$(this).find(".img-fit img").addClass("default-opacity");
}
})
.opacity-pointseven {
width: 100px;
height: 100px;
}
.default-opacity {
width: 50px;
height: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="featured-block">
<a href="/" class="featured-block__item cf">
<div class="featured-block__item-inner">
<figure class="featured-block__image img-fit">
<img src="">
</figure>
<div class="featured-block__content">
<h1 style="margin-bottom:0px;" class="featured-block__title">Trans Mountain Pipeline: NEB Releases New Report, Recommends Approval </h1>
<h1 class="featured-block__tag"> More Coverage</h1>
</div>
</div>
<div class="featured-block__item-inner">
<figure class="featured-block__image img-fit">
<img src="">
</figure>
<div class="featured-block__content">
<h1 style="margin-bottom:0px;" class="featured-block__title"></h1>
<h1 class="featured-block__tag"> More Coverage</h1>
</div>
</div>
</a>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)