使用数据属性根据具有多个 ID 的数组过滤 DOM 个节点

Filter DOM nodes based on an array with multiple Ids using data attributes

给定以下标记

<div class="group-one">
  <span data-id="1">
  <span data-id="2">
  <span data-id="3">
</div>

<div class="group-two">
  <span data-id="1">
  <span data-id="2">
  <span data-id="3">
</div>

我想使用 data-id

的数组来过滤节点

所以如果我有 ids=[1,2] 结果,我想要与数组中的节点相对应的两个节点,在其中一个组中。

ids=[1,2]
nodes = $(".group-one").children();
#nice way of filtering the nodes using ids array. With Jquery.filter or Underscore

我知道我可以遍历所有子节点并将每个节点 data-id 与 ids 数组进行比较。但我想知道这是否可以通过仅使用选择器或其他一些内衬类解决方案来实现。

谢谢!

只根据数据属性过滤?

var ids=[1,2];

$('div span').filter(function() {
    return ids.indexOf( $(this).data('id') ) !=  -1;
});

FIDDLE

只有 jQuery 个选择器的解决方案:

var filteredNodes = nodes.filter(function() {
    // Attributes are strings, so you have to convert int.
    var i = parseInt($(this).attr('data-id'));
    return $.inArray(i, ids) >= 0;
});