jQuery - 删除元素



jQuery 提供了 `remove()` 和 `empty()` 方法来从 HTML 文档中删除现有的 HTML 元素。

jQuery remove() 方法

jQuery 的 `remove()` 方法删除选定的元素及其子元素。

`remove()` 方法的语法如下:

$(selector).remove();

当您想要删除元素本身及其内部所有内容时,应该使用 `remove()` 方法。

摘要

考虑以下 HTML 内容:

<div class="container">
   <h2>jQuery remove() Method</h2>
   <div class="hello">Hello</div>
   <div class="goodbye">Goodbye</div>
</div>

如果我们应用 `remove()` 方法如下:

$( ".hello" ).remove();

它将产生以下结果:

<div class="container">
   <h2>jQuery remove() Method</h2>
   <div class="goodbye">Goodbye</div>
</div>

如果 `

` 内有任何数量的嵌套元素,它们也将被删除。

示例

让我们尝试以下示例并验证结果:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         $( ".hello" ).remove();
      });
   });
</script>
</head>
<body>
   <div class="container">
      <h2>jQuery remove() Method</h2>
      <div class="hello">Hello</div>
      <div class="goodbye">Goodbye</div>
   </div>
   <br>
   
   <button>Remove Text</button>
</body>
</html>

带过滤器的删除

我们还可以将选择器作为可选参数包含在 `remove()` 方法中。例如,我们可以将之前的 DOM 删除代码改写为:

让我们尝试以下示例并验证结果:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         $("div").remove(".hello");
      });
   });
</script>
</head>
<body>
   <div class="container">
      <h2>jQuery remove(selector) Method</h2>
      <div class="hello">Hello</div>
      <div class="goodbye">Goodbye</div>
   </div>
   <br>
   
   <button>Remove Text</button>
</body>
</html>

jQuery empty() 方法

jQuery 的 `empty()` 方法与 `remove()` 非常相似,它从文档中删除选定的元素及其子元素。此方法不接受任何参数。

`empty()` 方法的语法如下:

$(selector).empty();

当您想要删除元素本身及其内部所有内容时,应该使用 `empty()` 方法。

摘要

考虑以下 HTML 内容:

<div class="container">
   <h2>jQuery empty() Method</h2>
   <div class="hello">Hello</div>
   <div class="goodbye">Goodbye</div>
</div>

如果我们应用 `empty()` 方法如下:

$( ".hello" ).empty();

它将产生以下结果:

<div class="container">
   <h2>jQuery empty() Method</h2>
   <div class="goodbye">Goodbye</div>
</div>

示例

让我们尝试以下示例并验证结果:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         $( ".hello" ).empty();
      });
   });
</script>
</head>
<body>
   <div class="container">
      <h2>jQuery empty() Method</h2>
      <div class="hello">Hello</div>
      <div class="goodbye">Goodbye</div>
   </div>
   <br>
   
   <button>Remove Text</button>
</body>
</html>

jQuery HTML/CSS 参考

您可以在以下页面获得操作 CSS 和 HTML 内容的所有 jQuery 方法的完整参考:jQuery HTML/CSS 参考

广告
© . All rights reserved.