欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

jQuery基础:remove()与 detach()区别

发布时间:2023/12/10 编程问答 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 jQuery基础:remove()与 detach()区别 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1、detach()

  • detach() 方法移除被选元素,包括所有文本和子节点。
  • 这个方法会保留 jQuery 对象中的匹配的元素,因而可以在将来再使用这些匹配的元素。
  • detach() 会保留所有绑定的事件、附加的数据,这一点与 remove() 不同。
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><style>p{margin: 6px;background: yellow;}p.off{background: red;}</style> </head> <body><p>hello</p> how are<p>you?</p><button>按钮</button> </body> <script src="libs/jquery-1.8.3.min.js"></script> <script type="text/javascript">$(function(){$("p").click(function(){$(this).toggleClass("off");})var p;$("button").click(function(){if(p){p.appendTo("body");p = null;}else{p = $("p").detach();console.log(p);}})}); </script> </html>

2、remove()

  • 将匹配元素集合从DOM中删除。
  • 同时移除元素上的事件及 jQuery 数据。
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><style>p{margin: 6px;background: yellow;}p.off{background: red;}</style> </head> <body><p>hello</p> how are<p>you?</p><button>按钮</button> </body> <script src="libs/jquery-1.8.3.min.js"></script> <script type="text/javascript">$(function(){$("p").click(function(){$(this).toggleClass("off");})var p;$("button").click(function(){if(p){p.appendTo("body");p = null;}else{p = $("p").remove();console.log(p);}});//移除 =》加上,点击没反应,绑定的事件失效 }); </script> </html>

3、empty():移除匹配元素的所有子节点

4、unwrap():将匹配元素集合的父级元素删除,保留自身(和兄弟元素,如果存在)在原来的位置。

转载于:https://www.cnblogs.com/gao-xiong/p/5933284.html

总结

以上是生活随笔为你收集整理的jQuery基础:remove()与 detach()区别的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。