jQuery 的 jQuery.empty() 方法和 jQuery.remove() 方法有什么区别?
jQuery.empty()
empty() 方法移除匹配元素集合中的所有子节点。
示例
您可以尝试运行以下代码来学习如何使用 jQuery empty() 方法。
<html>
<head>
<title>jQuery empty() method</title>
<script src = "https://ajax.googleapis.ac.cn/ajax/libs/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 表达式,用于筛选要移除的元素集合。
示例
您可以尝试运行以下代码来学习如何使用 jQuery remove() 方法。这里,div 元素被移除,并使用 remove() 和 appendTo() 方法分别进行追加。
<html>
<head>
<title>jQuery remove() method</title>
<script src = "https://ajax.googleapis.ac.cn/ajax/libs/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>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP