jQuery中的jQuery.empty()和jQuery.remove()方法有什么区别?
jQuery.empty()
该empty()方法从匹配的元素集中删除所有子节点。
示例
您可以尝试运行以下代码来学习如何使用jQueryempty()方法:
<html>
<head>
<title>jQuery empty() method</title>
<script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).empty();
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;">ONE</div>
<div class = "div" style = "background-color:green;">TWO</div>
<div class = "div" style = "background-color:red;">THREE</div>
</body>
</html>jQuery.remove()
remove(expr)方法从DOM中删除所有匹配的元素。这不会将它们从jQuery对象中删除,而是允许您进一步使用匹配的元素。
这是此方法使用的所有参数的描述-
expr- 这是一个可选的jQuery表达式,用于过滤要删除的元素集。
示例
您可以尝试运行以下代码以了解如何使用jQueryremove()方法。在这里,分别使用remove()和appendTo()方法删除和附加div:
<html>
<head>
<title>jQuery remove() method</title>
<script src = "https://cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).remove().appendTo("#result");
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<p id = "result"> THIS IS TEST </p>
<hr />
<div class = "div" style = "background-color:blue;">ONE</div>
<div class = "div" style = "background-color:green;">TWO</div>
<div class = "div" style = "background-color:red;">THREE</div>
</body>
</html>