javascript - 带有选择器的 jQuery .remove() 不起作用

标签 javascript jquery

根据.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。那我在这里错过了什么?文档有错吗?我是不是误会了什么?

最佳答案

您误解了选择器参数的作用。它正在过滤第一组对象。

From the docs :

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/

相关文章:

javascript - 仅运行一次 javascript 函数

javascript - e.target.value 的值未定义

javascript - 事件选项卡背景在页面加载时发生变化

javascript - JS,函数返回 undefined 而不是 true 或 false

jquery - 如何在整个网站加载完成后淡入背景图像(n秒)

PHP 数组到 JQuery

javascript - 如何使用 Jquery 计算已启用的 CheckBoxList 项目的数量

javascript - 正则表达式从路径中排除文件夹

javascript - jQuery - 将函数数组传递给 ajax 成功回调

javascript - Joomla javascript css 类不更新