JQuery是一個很大強的工具庫,在工作中開發中,可是有些方法還是因爲不常用到,或是沒有注意到而被我們而忽略。
remove()和detach()可能就是其中的一個,可能remove()我們用得比較多,而detach()就可能會很少了
通過一張對比表來解釋2個方法之間的不同
方法名 |
參數 |
事件及數據是否也被移除 |
元素自身是否被移除 |
remove |
支持選擇器表達 |
是 |
是(無參數時),有參數時要根據參數所涉及的範圍 |
detach |
參數同remove |
否 |
情況同remove |
remove:移除節點
detach:移除節點
<html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> <style type="text/css"> p { border: 1px solid red; } </style> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <h3>給頁面2個p元素節點綁定點擊事件,點擊後彈出自己本身的節點內容</h3> <p>元素p1,同時綁定點擊事件</p> <p>元素p2,同時綁定點擊事件</p> <h3>通過點擊2個按鈕後觀察方法處理的區別</h3> <button>點擊通過remove處理元素p1</button> <button>點擊通過detach處理元素p2</button> </body> <script type="text/javascript"> //給頁面上2個p元素都綁定時間 $('p').click(function (e) { alert(e.target.innerHTML) }) $("button:first").click(function () { var p = $("p:first").remove(); p.css('color', 'red').html('p1通過remove處理後,點擊該元素,事件丟失') $("body").append(p); }); $("button:last").click(function () { var p = $("p:first").detach(); p.css('color', 'blue').text('p2通過detach處理後,點擊該元素事件存在') $("body").append(p); }); </script> </script> </ html >