天天看点

jquery的remove和detach的方法区别

前面写过一篇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不会