[JS][jQuery]remove()與 empty()的區別,jqueryempty

來源:互聯網
上載者:User

[JS][jQuery]remove()與 empty()的區別,jqueryempty

要用到移除指定元素的時候,發現empty()與remove([expr])都可以用來實現。可仔細觀察效果的話就可以發現。

empty()是只移除了 指定元素中的所有子節點,拿$("p").empty()來說,他只是把<p>dsfsd</p>中的文本給移除了,而留下 了<p></p>,仍保留其在dom中所佔的位置。

remove([expr])則是把其從dom中刪除,而不會保留其所佔的位置。
例:
<p>Hello</p>
World
<p>welcome</p> 
執行$("p").empty()其結果是
<p></p>
World
<p></p> 

執行$("p").remove()其結果是
World
jquery裡使用empty()與html("")有什不同?

empty()、html("")和text("")在刪除匹配元素內內容時是一樣的。jQuery源碼中實現有所不同,但效果相同。你可以測試一下
源碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "www.w3.org/...al.dtd">
<html xmlns="www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<script src="../scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script>
$(function(){
$('#btnEmpty').click(function(){
$('#aim').empty();
alert("empty()");
});
$('#btnHtml').click(function(){
$('#aim').html("");
alert('html("")');
});
$('#btnText').click(function(){
$('#aim').text("");
alert('text("")');
});
});

</script>
</head>

<body>
<div id="aim">

<ul>
<li>111111111</li>
<li>222222222</li>
<li>333333333</li>
<li>444444444</li>
</ul>

</div>
<button id='btnEmpty'>empt......餘下全文>>
 
jquery之empty與remove不同

empty是清空元素的內容,remove是連著這個元素一起刪除。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.