码迷,mamicode.com
首页 > 其他好文 > 详细

detach与remove区别,以及detach保留被删除的元素数据,使用

时间:2017-10-09 14:16:44      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:else   rtb   另一个   document   使用   fun   strong   back   16px   

detach() 会保留所有绑定的事件、附加的数据,这一点与 remove() 不同。

remove掉元素后,元素再也找不回了。但是detach还能找回来,还能保留下来。

实现方式如下代码:

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    var p;flag=1;
  $("button").click(function(){
    if(flag==1)
    {
      p=$("p").detach();
      flag=0;
    }
   else{
      flag=1;
      p.insertBefore("button");
   }
  });
});
</script>
</head>

<body>
<p>This is a paragraph.</p>
<button>删除 p 元素</button>
</body>
</html>

可见,detach方法会返回被删除元素的数据,可以赋值给一个变量,然后,插入到另一个元素前面。

detach与remove区别,以及detach保留被删除的元素数据,使用

标签:else   rtb   另一个   document   使用   fun   strong   back   16px   

原文地址:http://www.cnblogs.com/alsf/p/7640648.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!