jQuery empty()方法
jQuery empty()方法用于从所选元素中移除所有子节点和内容。该方法不会移除元素本身。
如果您想要在不移除数据和事件的情况下移除元素,应使用detach()方法。
如果您想要移除元素以及其数据和事件,应使用remove()方法。
语法 :
$(selector).empty()
jQuery empty()方法的示例1
我们来看一个例子来演示jQuery empty()方法。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
(document).ready(function(){("button").click(function(){
$("div").empty();
});
});
</script>
</head>
<body>
<div style="height:150px;background-color:yellow">
Twinkle, twinkle, little star,<br/>
How I wonder what you are!</br>
Up above the world so high,<br/>
Like a diamond in the sky.<br/>
Twinkle, twinkle, little star,<br/>
How I wonder what you are!<br/>
<p><b>This poem is written inside the div.</b></p>
</div>
<p>This paragraph is written outside the div.</p>
<button>Execute empty() method to remove the content of div element.</button>
</body>
</html>
jQuery empty()方法的示例2
<!DOCTYPE html>
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
(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 any of the box given below to see the result:</p>
<div class="div" style="background-color:yellow;">Click me!</div>
<div class="div" style="background-color:green;">Click me!</div>
<div class="div" style="background-color:red;">Click me!</div>
</body>
</html>