gpt4 book ai didi

html - 按属性条件删除某些div

转载 作者:太空狗 更新时间:2023-10-29 15:34:39 25 4
gpt4 key购买 nike

我有这样的东西

<div data-count="5">Something</div>
<div data-count="10">Something</div>
<div data-count="15">Something</div>
<div data-count="20">Something</div>
<div data-count="25">Something</div>

如何删除“data-count”属性值小于 15 的 div?

最佳答案

这样效率更高,因为它只选择具有 data-count 属性的 div,并且只为每个元素构造一次 jQuery 对象:

$('div[data-count]').each(function () {
var $this = $(this);

if ($this.attr('data-count') < 15) {
$this.remove();
}
});

演示:

$('button').on('click', function () {
$('div[data-count]').each(function () {
var $this = $(this);

if ($this.attr('data-count') < 15) {
$this.remove();
}
});
});
div[data-count]:before {
content: "<div data-count=\"" attr(data-count) "\">";
}

div[data-count]:after {
content: "</div>";
}
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<button type="button">Remove data-count less than 15</button>
<div data-count="5">Something</div>
<div data-count="10">Something</div>
<div data-count="15">Something</div>
<div data-count="20">Something</div>
<div data-count="25">Something</div>

原生 JavaScript 的替代解决方案:

var divs = document.querySelectorAll('div[data-count]'),
div, i;

for (i = 0; i < divs.length; i++) {
div = divs[i];
if (div.getAttribute('data-count') < 15) {
// this will not affect iteration because querySelectorAll is a non-live NodeList
div.parentNode.removeChild(div);
}
}

演示:

var button = document.querySelector('button');

button.addEventListener('click', function () {
var divs = document.querySelectorAll('div[data-count]'),
div, i;

for (i = 0; i < divs.length; i++) {
div = divs[i];
if (div.getAttribute('data-count') < 15) {
// this will not affect iteration because querySelectorAll is a non-live NodeList
div.parentNode.removeChild(div);
}
}
});
div[data-count]:before {
content: "<div data-count=\"" attr(data-count) "\">";
}

div[data-count]:after {
content: "</div>";
}
<button type="button">Remove data-count less than 15</button>
<div data-count="5">Something</div>
<div data-count="10">Something</div>
<div data-count="15">Something</div>
<div data-count="20">Something</div>
<div data-count="25">Something</div>

关于html - 按属性条件删除某些div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31283284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com