我有一个类似的元素列表:
<article id="post-647" class="brand-search-result brand-alaffia hidden"></article>
<article id="post-647" class="brand-search-result brand-alaffia hidden"></article>
<article id="post-647" class="brand-search-result brand-alaffia hidden"></article>
<article id="post-650" class="brand-search-result brand-alter-eco hidden"></article>
<article id="post-650" class="brand-search-result brand-alter-eco hidden"></article>
<article id="post-650" class="brand-search-result brand-alter-eco hidden"></article>
现在我想要的是找到每个唯一ID的第一个并删除隐藏的类。这是我到目前为止在jquery中所拥有的:
(function(){
$("[id^=post-]").each(function(){
$(this).first(".brand-search-result").removeClass('hidden');
});
})();
唯一的问题是每个有意义的文章元素都会运行。有什么建议吗?
答案 0 :(得分:1)
在某处存储唯一帖子的信息。跳过未来的。
var processedPosts = {};
(function(){
$("[id^=post-]").each(function(){
var id = $(this).prop("id") //modify to use unique ids (as suggested in comments)
if (!processedPosts[id]) {
$(this).first(".brand-search-result").removeClass('hidden');
processedPosts[id] = true;
}
});
})();
答案 1 :(得分:0)
你走近了。
'#'+ $(this).attr('id')
'#'加上id,然后我们将它用作选择器。
$("[id^=post-]").each(function() {
$( '#' + $(this).attr('id') ).first('.brand-search-result').removeClass('hidden');
});
.hidden { display: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<article id="post-647" class="brand-search-result brand-alaffia hidden">post-647</article>
<article id="post-647" class="brand-search-result brand-alaffia hidden">post-647</article>
<article id="post-647" class="brand-search-result brand-alaffia hidden">post-647</article>
<article id="post-650" class="brand-search-result brand-alter-eco hidden">post-650</article>
<article id="post-650" class="brand-search-result brand-alter-eco hidden">post-650</article>
<article id="post-650" class="brand-search-result brand-alter-eco hidden">post-650</article>
您不需要存储在数组中并检查它。