HOWTO · jQuery
jQuery remove() 方法
本教程演示如何在 jQuery 中删除元素。
本页内容
remove() 方法从 jQuery 中的 DOM 中删除元素。类似地,empty() 方法仅删除 DOM 中选定元素的子元素。
本教程演示了如何在 jQuery 中使用 remove 和 empty 方法。
jQuery remove() 方法
remove() 方法可以从 DOM 中删除选定的元素。该方法将删除选定的元素和元素内的所有内容。
此方法的语法如下。
$(selector).remove(selector)
其中 selector 是一个可选参数,指定是否删除一个或多个元素,如果要删除的元素不止一个,我们可以用逗号分隔它们。让我们尝试一个 remove() 方法的示例。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#RemoveDiv").remove();
});
});
</script>
</head>
<body>
<div id="RemoveDiv" style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">
<h1> This Div Will be Removed </h1>
<p>Paragraph one in the Div.</p>
<p>Paragraph two in the Div.</p>
</div>
<br>
<div style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">
<h1> This Div Will not be Removed </h1>
<p>Paragraph one in the Div.</p>
<p>Paragraph two in the Div.</p>
</div>
<button>Remove Div</button>
</body>
</html>
上面的代码将删除选定的 div 及其子元素。见输出:
正如我们所见,remove() 方法删除了选定元素内的所有元素。另一种方法 empty() 仅删除子元素。
jQuery empty() 方法
empty() 方法可以从选定元素中删除所有子元素。它还会删除子元素内的内容。
empty() 方法的语法如下。
$('selector').empty();
selector 可以是 id、类或元素名称,让我们尝试 empty 方法的示例。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#RemoveDiv").empty();
});
});
</script>
</head>
<body>
<div id="RemoveDiv" style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">
Hello this is the div content
<h1> This Div Content Will be Removed </h1>
<p>Paragraph one in the Div.</p>
<p>Paragraph two in the Div.</p>
</div>
<br>
<div style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">
<h1> This Div Content Will not be Removed </h1>
<p>Paragraph one in the Div.</p>
<p>Paragraph two in the Div.</p>
</div>
<button>Remove Div</button>
</body>
</html>
上面的代码将只删除 div 的子内容,而不是 div 本身。见输出: