前面寫過一篇jQuery文檔處理相關的文章,介紹了一下文檔操作中删除相關的api。
那麼remove與detach的差別最主要的是什麼呢?
我們先做個測試,動動手比死的理論影響深刻。
<div id="test" style="width:200px;height:100px;">預設文字</div>
<input type="button" id="detach" value="detach" />
<div id="parent"></div>
$(function(){
//綁hover
$('#test').hover(function(){
$(this).html("hover狀态");
},function(){
$(this).html("原始的内容");
});
//調用detach;
$('#detach').click(function(){
//綁detach
//var test = $('#test').detach();
//綁remove
var test = $('#test').remove();
$('#parent').append(test);
});
});
最後發現:
- detach之後,test的hover事件還存在
- remove之後,test的hover事件不存在
注釋:detach與remove傳回的都是比對的jQuery對象
結論:
- detach對所有綁定的事件,附加的資料都會保留,而remove不會