我正在一个网站上工作,我想检查其中的元素是否有任何内容。
下面是我的html代码。我已经提到 condition#1 如果类 featured-block__title
和 featured-block__tag< 应该通过脚本添加
里面有内容。 opacity-pointseven
类
<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>
关于javascript - 如果元素中包含内容,如何在 Javascript/jQuery 中添加类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55114183/