gpt4 book ai didi

javascript - 使用 jQuery 删除某个元素下面的元素

转载 作者:行者123 更新时间:2023-12-03 04:01:40 25 4
gpt4 key购买 nike

我有下一个代码:

$(function () {
$('#delete-button').click(function () {
deleteElementsBelow('#parent-container', 'element-2');
});

function deleteElementsBelow(parentContainerSelector, deleteBelowSelector) {
var deleteOthers = false;
$(parentContainerSelector).children().each(function () {
var $elem = $(this);

if (deleteOthers) {
$elem.remove();
} else if ($elem.hasClass(deleteBelowSelector)) {
deleteOthers = true;
}
});
}
});
#parent-container div {
background-color: red;
width: 20px;
height: 20px;
margin: 10px;
}

#parent-container div:nth-child(2n) {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent-container">
<div class="element-1"></div>
<div class="element-2"></div>
<div class="element-3"></div>
<div class="element-4"></div>
<button id="delete-button" type="button">Delete</button>
</div>

是否可以通过 native jQuery API 执行 deleteElementsBelow 操作?

最佳答案

您可以使用诸如 $(parentContainerSelector + "."+deleteBelowSelector).nextAll("div").remove() 之类的内容来删除目标之后的所有 div元素。

这将删除带有 element-3element-4 类的 div

$(function () {
$('#delete-button').click(function () {
deleteElementsBelow('#parent-container', 'element-2');
});

function deleteElementsBelow(parentContainerSelector, deleteBelowSelector) {
var deleteOthers = false;
$(parentContainerSelector + " ." +deleteBelowSelector).nextAll("div").remove()
}
});
#parent-container div {
background-color: red;
width: 20px;
height: 20px;
margin: 10px;
}

#parent-container div:nth-child(2n) {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent-container">
<div class="element-1"></div>
<div class="element-2"></div>
<div class="element-3"></div>
<div class="element-4"></div>
<button id="delete-button" type="button">Delete</button>
</div>

关于javascript - 使用 jQuery 删除某个元素下面的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44696496/

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