首页 > 解决方案 > 从jquery中的列表中省略重复项

问题描述

使用 jquery,给出以下列表:

<div>cat</div>
<div>dog</div>
<div>horse</div>
<div>cat</div>
<div>goat</div>
<div>mouse</div>

我们如何遍历它们并省略 -hide()remove()- 重复,即。“猫” ?

标签: jquery

解决方案


鉴于,

<div class="my-list">
 <div>cat</div>
 <div>dog</div>
 <div>horse</div>
 <div>cat</div>
 <div>goat</div>
 <div>mouse</div>
</div>

那么你也能:

const $list = $('.my-list');
const showed = [];
$list.find('div').each(function() {
   if ( $.inArray($(this).text(), showed) === -1 ) {
      showed.push($(this).text());
   } else {
      $(this).hide();  // or .remove()
   }
});

推荐阅读