根据.remove() | jQuery API Documentation , 将选择器作为可选参数包含在 .remove()
中是完全有效的。引用:
We can also include a selector as an optional parameter. For example, we could rewrite the previous DOM removal code as follows:
$( "div" ).remove( ".hello" );
所以我写了 2 个 div 来测试它:
<div id="div1">test
<div id="div2">Remove</div>
</div>
将其用作 jQuery:
$( document ).ready(function() {
$( "#div1" ).remove( "#div2" );
});
它没有按预期删除 div。结果是:
test
Remove
改为使用:
$( document ).ready(function() {
$("#div2").remove();
});
按预期删除 div。那我在这里错过了什么?文档有错吗?我是不是误会了什么?
最佳答案
您误解了选择器参数的作用。它正在过滤第一组对象。
A selector expression that filters the set of matched elements to be removed.
因此,您的 "#div2"
选择器不作为 "#div1"
元素的一部分存在。例如,假设我有以下内容:
<div class="red">Red</div>
<div class="red">Red</div>
<div class="red">Red</div>
<div class="red notneeded">Red</div>
<div class="red notneeded">Red</div>
<div class="red">Red</div>
然后,我调用以下内容:
$(function () {
$("div.red").remove(".notneeded");
});
我会留下以下内容:
<div class="red">Red</div>
<div class="red">Red</div>
<div class="red">Red</div>
<div class="red">Red</div>
因此,jQuery 匹配集是所有具有 red
类的 div - 第二个选择器 (".notneeded"
) 将过滤第一个匹配的集使用 notneeded
类 - 然后它将删除它们。
关于javascript - 带有选择器的 jQuery .remove() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32833551/