4-3 DOM节点删除之empty和remove区别
本节编程练习不计算学习进度,请电脑登录imooc.com操作

DOM节点删除之empty和remove区别

要用到移除指定元素的时候,jQuery提供了empty()与remove([expr])二个方法,两个都是删除元素,但是两者还是有区别

empty方法

remove方法

以上就是二者的区别,我们具体通过右边代码部分加深理解

任务

  1. <!DOCTYPE html>
  2. <html>
  3.  
  4. <head>
  5. <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  6. <title></title>
  7. <script src="https://www.imooc.com/static/lib/jquery/1.9.1/jquery.js"></script>
  8. <style>
  9. .left,
  10. .right {
  11. width: 300px;
  12. }
  13.  
  14. .left div,
  15. .right div {
  16. width: 100px;
  17. height: 90px;
  18. padding: 5px;
  19. margin: 5px;
  20. float: left;
  21. border: 1px solid #ccc;
  22. }
  23.  
  24. .left div {
  25. background: #bbffaa;
  26. }
  27.  
  28. .right div {
  29. background: yellow;
  30. }
  31. </style>
  32. </head>
  33.  
  34. <body>
  35. <h2>通过empty与remove移除元素</h2>
  36. <div class="left">
  37. <button id="bt1">点击通过jQuery的empty移除内部P元素</button>
  38. <button id="bt2">点击通过jQuery的remove移除整个节点</button>
  39. </div>
  40. <div class="right">
  41. <div id="test1">
  42. <p>p元素1</p>
  43. <p>p元素2</p>
  44. </div>
  45. <div id="test2">
  46. <p>p元素3</p>
  47. <p>p元素4</p>
  48. </div>
  49. </div>
  50. <script type="text/javascript">
  51. $("#bt1").on('click', function() {
  52. //删除了2个p元素,但是本着没有删除
  53. $("#test1").empty()
  54. })
  55.  
  56. $("#bt2").on('click', function() {
  57. //删除整个节点
  58. $("#test2").remove()
  59. })
  60. </script>
  61. </body>
  62.  
  63. </html>
  64.  
下一节