empty() 方法會移除選中元素的所有子節點(包括元素節點、文本節點、註釋節點),但保留元素自身。這比 html("") 更語義化,也比手動遍歷移除更高效。
| 方法 | 清空內容 | 保留元素 | 移除事件/數據 | 返回值 |
|---|---|---|---|---|
empty() | ✓ | ✓ | ✓ | jQuery 對象(鏈式) |
html("") | ✓ | ✓ | ✓ | jQuery 對象 |
remove() | ✓ | ✗ | ✓ | jQuery 對象 |
detach() | ✓ | ✗ | ✗ | jQuery 對象 |
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").empty();
});
});
</script>
</head>
<body>
<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
</div>
<br>
<button>Empty the div element</button>
</body>
</html>
<!-- 執行前 -->
<div id="div1">
文本節點
<p>段落1</p>
<p>段落2</p>
<!-- 註釋 -->
</div>
<!-- 執行 $("#div1").empty() 後 -->
<div id="div1"></div> <!-- 完全空標籤 -->
$("#list").empty().append(newItems) 避免殘留舊數據$("#modal").empty() 釋放內存$("#editor").empty()大量子元素時,empty() 比 html("") 略快,因為它直接操作 DOM 節點而非解析 HTML 字符串。但現代瀏覽器差異已極小,優先考慮代碼可讀性。