【问题标题】:JavaScript filtering by comparing two arraysJavaScript 通过比较两个数组进行过滤
【发布时间】:2016-10-11 07:27:07
【问题描述】:

DOM:

<div class='myDiv' data-catid='1,2,3'></div>
<div class='myDiv' data-catid='4,5'></div>
<div class='myDiv' data-catid='1,5,7'></div>
<div class='myDiv' data-catid='8,9'></div>
<div class='myDiv' data-catid='2,3,4'></div>

JS:

var filters = [2, 4];

我想遍历divs,并隐藏在data-catid 中没有两个类别ID 的那些。

到目前为止我有这个:

$('.myDiv').each(function(i, el){               

  var itemCategories = $(el).data('catId').split(',');

  // Do check and then hide with $(el).css('visibility', 'hidden') 
  // if doesn't contain both filter id's in 'itemCategories';

});

【问题讨论】:

  • 很高兴看看你到目前为止是如何尝试过滤的......

标签: javascript jquery


【解决方案1】:

使用 filter() 方法和 javascript Array#every 方法(也可以使用 Array#some 方法)。

var filters = [2, 4];

// get all elements with class `myDiv`
$('.myDiv')
  // filter out elements
  .filter(function() {
    // generate array from catid attribute
    var arr = $(this)
      // get data attribute value
      .data('catid')
      // split based on `,`
      .split(',')
      // parse the string array, it's optional 
      // if you are not parsing then convert Number to 
      // String while using with indexOf
      .map(Number);
    // check all catid presents 
    return !filters.every(function(v) {
      // check index of elements
      return arr.indexOf(v) > -1;
    });
    // or with `some` method 
    // return filters.some(function(v) { return arr.indexOf(v) === -1; });  
    // hide the elements
  }).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='myDiv' data-catid='1,2,3'>1</div>
<div class='myDiv' data-catid='4,5'>2</div>
<div class='myDiv' data-catid='1,5,7'>3</div>
<div class='myDiv' data-catid='8,9'>4</div>
<div class='myDiv' data-catid='2,3,4'>5</div>

仅供参考:对于旧版浏览器,请查看polyfill option of every method

【讨论】:

  • 感谢您的回答,但是当我运行它时出现此错误:“Uncaught TypeError: $(...).data(...).split is not a function”
  • @DeanGibson : 虽然将 $('.myDiv') 更改为 $('.myDiv[data-catid]')
【解决方案2】:

您可以使用 jquery .filter() 而不是 .each() 来过滤选定的元素,并使用 String.prototype.indexOf() 来检查数组中是否存在值。

var filters = [2, 4];
$('.myDiv').filter(function(){               
    var num = $(this).data('catid').split(',').map(Number);  
    return num.indexOf(filters[0]) == -1 || num.indexOf(filters[1]) == -1
}).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='myDiv' data-catid='1,2,3'>1</div>
<div class='myDiv' data-catid='4,5'>2</div>
<div class='myDiv' data-catid='1,5,7'>3</div>
<div class='myDiv' data-catid='8,9'>4</div>
<div class='myDiv' data-catid='2,3,4'>5</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-03
    • 2015-08-04
    • 1970-01-01
    • 2021-11-18
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多