<!DOCTYPE html> <html> <head> <script src="/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").detach(); }); }); </script> </head> <body> <p>Hello Guys!</p> <p>This is lidihuo.com</p> <button>Click here to detach all p elements</button> </body> </html>
输出:
Hello Guys!
This is lidihuo.com
jQuery detach()示例2
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>detach demo</title> <style> p { background: lightpink; margin: 6px 0; } </style> <script src="/jquery-1.10.2.js"></script> </head> <body> <p>Hello Guys!</p> <p>This is lidihuo.com</p> <button>Click here to Attach/detach all p elements. </button> <script> $("p").click(function() { $( this ).toggleClass( "off"); }); var p; $("button").click(function() { if ( p ) { p.appendTo( "body"); p = null; } else { p = $("p").detach(); } }); </script> </body> </html>
Hello Guys!
This is lidihuo.com
detach()和remove()方法之间的差异
让我们以一个示例来清除detach()和remove()方法之间的区别:
jQuery detach()示例3
<!DOCTYPE html> <html> <head> <script src="/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("body").append($("#p1").detach()); }); $("#btn2").click(function(){ $("body").append($("#p2").remove()); }); $("p").click(function(){ $(this).animate({fontSize: "+=1px"}) }); }); </script> </head> <body> <p id="p1"><b>This paragraph will keep its click event even after it is moved.</b></p> <p id="p2">This paragraph will not keep its click event after it is moved.</p> <button id="btn1">Detach and append p element</button> <button id="btn2">Remove and append p element</button> </body> </html>
This paragraph will keep its click event even after it is moved.
This paragraph will not keep its click event after it is moved.