detach()函數用於從文檔中移除匹配的元素,與remove()相比,detach()函數不會移除與元素關聯綁定的附加數據( data()函數 )和事件等(remove()會移除)。
如果要刪除以後不再利用的元素時,使用empty或者remove。
一、detach()的使用場合
當我們要對一個元素進行大規模的增刪改的時候,我們可以用detach將這個元素提取出來,然後在這個元素上進行操作,而不是在整個dom文檔中進行操作。
好處就是:減少對整個dom文檔的修改,從而減少頁面重繪;
二、實例
首先對#container元素綁定click事件,然後利用detach將其脫離文檔,然後再創建兩個child元素,追加到#container元素中,最後將#container重新添加到body
<!DOCTYPE html>
<head>
<title>jQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style>
div.monkey, #container {}{
width:120px;
height:120px;
line-height:60px;
}
div.monkey {}{
border:1px solid black;
}
</style>
</head>
<body>
<div class="monkey"> </div>
<div id="container"> </div>
<script src="jquery-1.12.0.js"></script>
<script>
$(function(){
//事件代理
$('#container').on('click',function( event ){
console.log( $(event.target).text() );
});
//利用detach將container從dom文檔中剝離開
var container = $('#container').detach();
var child1 = '<div>I am Monkey</div>';
var child2 = '<div>Monkey is me</div>';
//將child1、child2插入container中
$(container).append( child1 )
.append( child2 );
//將container重新插入body中
$('body').append( container );
});
</script>
</body>
</html>
文章轉載自:jquery中使用detach 移除元素的使用場合 http://www.studyofnet.com/news/1225.html