empty(),remove()和detach()的區別
empty():清空匹配的元素集合中所有的子節點,自身節點和事件都未被刪除。
remove():這個方法不會把匹配的元素從jQuery對象中刪除,因而可以在將來再使用這些匹配的元素。但除了這個元素本身得以保留之外,其他的比如綁定的事件,附加的數據等都會被移除。
detach():這個方法不會把匹配的元素從jQuery對象中刪除,因而可以在將來再使用這些匹配的元素。與remove()不同的是,所有綁定的事件、附加的數據等都會保留下來。
舉個栗子 :
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>empty(),remove()和detach()的區別</title> <style type="text/css"> div{ width:200px; height:200px; border:5px solid green; } </style> <script typet="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> $(function () { $("#first").hover(function () { $(this).text("我是hover"); }); //使用 remove() hover()事件也會被刪除 // apple = $("#first").remove(); //使用detach() hover()事件會保存下來 // apple = $("#first").detach(); // 使用empty只是清空了div的內容,節點和事件都未被刪除 apple = $("#first").empty(); $("body").append(apple);//將id為"first"的div插入到body中。 $("#btn").click(function(){ var a=$("div"); alert(a.length);//結果始終是2。 }) }); </script> </head> <body> <div id="first">我是第一</div> <div id="second">我是第二</div> <button id="btn">查看div的數量</button> </body> </html>