jQuery:从数组中排除具有id的元素

jQuery: Excluding the elements having id from an array

本文关键字:id 元素 排除 数组 jQuery      更新时间:2023-09-26

我想找到id不包括在数组列表中的所有div。

示例:

Array: [1, 2, 5]

分区:

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>

我只想找到不包括的div:3和4。


我知道我能做到:

var array = [1, 2, 5];
var stringNot = '';
$.each(array, function (index, element) {
    stringNot.concat('#' + element + ',');
}
stringNot = stringNot.replace(/,'s*$/, ''); // Removing last comma.
$('div').not(stringNot);

但是,有一个简单的方法吗?

您可以使用not()排除元素

从匹配的元素集中删除元素。

步骤:

  1. 在这种情况下,选择所有元素div s
  2. 使用join连接使用#,的数组元素,因为数组中的元素是id
  3. 在连接字符串的开头添加#,对于数组中的第一个元素,因为join不会添加它

代码和演示

var arr = [1, 2, 5];
$('div').not('#' + arr.join(',#')).addClass('included');
div {
  padding: 5px;
  background: red;
  width: 20px;
  height: 20px;
  margin: 5px;
  text-align: center;
}
.included {
  background: green;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
<div id="4">4</div>
<div id="5">5</div>

尽管您已经选择了答案,但以下是您在Javascript(而不是jQuery(中的操作方法:

var idList = [1, 2, 5], // array of ids
    divs = document.querySelectorAll('div'), // select all divs
    notFound;
notFound = [].filter.call(divs, function(div) { // filter into a new array
    return (idList.indexOf((+div.id)) < 0); // where numeric id is not found
});

代码段

var idList = [1, 2, 5], divs = document.querySelectorAll('div'),
    notFound;
notFound = [].filter.call(divs, function(div) {
  return (idList.indexOf((+div.id)) < 0);
});
[].forEach.call(notFound, function(div) {
  div.setAttribute("class", "notfound");
});
.notfound { background-color: yellow; }
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
<div id="4">4</div>
<div id="5">5</div>

你能使用jQuery吗?您可以尝试使用:not()选择器

jQuery API:not((