2016-04-28 45 views
-1

类的第一个元素我有元素的列表是这样的:的jQuery找到唯一的ID

<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'); 
    }); 
})(); 

唯一的问题是每一篇文章元素这是有道理的这一运行。有什么建议么?

+6

建议:** IDS必须是唯一的** – theblindprophet

+0

,如果你想选择的唯一的字符串使用类 – fdfey

+0

@theblindprophet差了一点更多的元素 - 除了,它应该比一个建议了。 – Alfie

回答

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; 
    } 
}); 

})();

+0

谢谢@ThiagoPXP多数民众赞成正是我想要的! – rhysclay

0

你靠近。

'#' + $(本).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>

你不需要在阵列来存储和对证。

JS Fiddle