我有一个与我的div data-id相同id的数组:我需要为我的数组做一个循环,只有没有类".empty-box"的值。在这种情况下,我需要循环我的数组值为1,2和3,因为4和5有相同的div空框的值。
<div class="box" data-id="1"> </div>
<div class="box" data-id="2"> </div>
<div class="box" data-id="3"> </div>
<div class="box empty-box" data-id="4"> </div>
<div class="box empty-box" data-id="5"> </div>
var emptyBoxes = $('.empty-box')
var myArray = [
{id:1},
{id:2},
{id:3},
{id:4},
{id:5}
]
我的解决方案是这样的,但我不确定是不是最好的方法:
var myArray = [
{id:1},
{id:2},
{id:3},
{id:4},
{id:5}
]
var emptyBoxes = $('.empty-box');
var ids = [];
emptyBoxes.each(function(i, v){
ids.push($(v).data('id'));
})
var list = myArray.filter(function(el) {return !ids.includes(el.id)};
你有什么解决办法吗?使用jQuery,您可以访问:not
选择器。
const nonEmptyBoxes = $('.box:not(.empty-box)');
您可以使用document.querySelectorAll('div.box[data-id]:not(.empty-box)')
来获取所有非空且具有id的框。
我添加了一个示例来显示速度差异。
var myArray = [
{id:1},
{id:2},
{id:3},
{id:4},
{id:5}
]
console.time('old');
var emptyBoxes = $('.empty-box');
var ids = [];
emptyBoxes.each(function(i, v){
ids.push($(v).data('id'));
})
var list = myArray.filter(function(el) {return !ids.includes(el.id)});
console.log(list);
console.timeEnd('old');
console.time('new');
const validBoxes = document.querySelectorAll('div.box[data-id]:not(.empty-box)');
let newList = [];
validBoxes.forEach((element) => {newList.push({id: element.getAttribute('data-id')})});
console.log(newList);
console.timeEnd('new');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box" data-id="1"> </div>
<div class="box" data-id="2"> </div>
<div class="box" data-id="3"> </div>
<div class="box empty-box" data-id="4"> </div>
<div class="box empty-box" data-id="5"> </div>