如果我有一个 JQuery 对象,其中包含 DOM 中已有的元素,则删除函数将正确地将它们从中删除。
但是,我想删除尚未添加到 DOM、仅存在于 JQuery 对象中的特定元素,如下所示:
var $div = $("<div><span class='sample'></span></div>");
$div.remove(".sample");
console.log($div.html()); // prints out the original HTML, inner span is not removed
最佳答案
如果您将选择器传递给 remove()
,那么选择器将应用于您的案例 $div
中不包含 的元素传递集>sample
元素,它是 $div
引用的元素的后代。所以你需要使用 .find() 来查找元素并将其删除
var $div = $("<div><span class='sample'></span>some content</div>");
$div.find(".sample").remove();
$('#result').text($div.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>
关于javascript - 如何从尚未添加到 DOM 的 JQuery 对象中删除特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25911632/