我有一些文章被展示了两次,我想用jQuery隐藏其中一篇。它们都具有相同的数据ID,因此我想找到一种比较它们的方法(data-id =“134”)。另外,我不会知道ID,所以我不能写(如果data-id === 134例如)有没有一个好的方法来做到这一点?这是我现在的代码:
var article1_id = $('.older_articles ajax_article active').data("id");
var article2_id= $('.featured_article').data("id");
if article1_id === article2_id {
$(article1_id).css('display', 'none');
} else {
$(article1_id).css('display', 'block');
}
答案 0 :(得分:0)
如果我理解正确,你可以在一行JQuery中完成。这会隐藏.old_articles
中data-id
属性与您的精选文章相匹配的任何元素...
$('.older_articles [data-id="' + $('.featured_article').data('id') + '"]').css('display', 'none');
示例...
$('.older_articles [data-id="' + $('.featured_article').data('id') + '"]').css('opacity', '0.5');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="older_articles">
<h4>Old articles</h4>
<div data-id="134">Featured article duplicate - data-id 134</div>
<div data-id="135">Non-Duplicated article- data-id 135</div>
</div>
<div>
<h4>Featured articles</h4>
<div class="featured_article" data-id="134">I'm featured! - data-id 134
</div>
如果您需要隐藏多个元素,可以使用.each()
遍历所有文章......
$('.featured_article').each(function() {
$('.older_articles [data-id="' + $(this).data('id') + '"]').css('opacity', '0.5');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="older_articles">
<h4>Old articles</h4>
<div data-id="134">Article - data-id 134</div>
<div data-id="135">Article - data-id 135</div>
<div data-id="137">Article - data-id 137</div>
<div data-id="138">Article - data-id 138</div>
</div>
<div>
<h4>Featured articles</h4>
<div class="featured_article" data-id="134">I'm featured! - data-id 134
<div class="featured_article" data-id="135">I'm featured! - data-id 135
<div class="featured_article" data-id="136">I'm featured! - data-id 136
<div class="featured_article" data-id="138">I'm featured! - data-id 138
</div>