本文概述
jQuery empty()方法用于从所选元素中删除所有子节点和内容。此方法不会删除元素本身。
如果要删除元素而不删除数据和事件, 则应使用detach()方法。
如果要删除元素及其数据和事件, 则应使用remove()方法。
句法:
$(selector).empty()
jQuery empty()方法的示例
让我们以一个示例来演示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>
立即测试
评论前必须登录!
注册