1、detach()的使用场合
html
当咱们要对一个元素进行大规模的增删改的时候,咱们能够用detach将这个元素提取出来,而后在这个元素上进行操做,而不是在整个dom文档中进行操做。jquery
好处就是:减小对整个dom文档的修改,从而减小页面重绘;app
2、实例dom
首先对#container元素绑定click事件,而后利用detach将其脱离文档,而后再建立两个child元素,追加到#container元素中,最后将#container从新添加到bodyui
<!DOCTYPE html> <head> <title>jQuery</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style> div.monkey, #container {}{ width:120px; height:120px; line-height:60px; } div.monkey {}{ border:1px solid black; } </style> </head> <body> <div class="monkey"> </div> <div id="container"> </div> <script src="jquery-1.12.0.js"></script> <script> $(function(){ //事件代理 $('#container').on('click',function( event ){ console.log( $(event.target).text() ); }); //利用detach将container从dom文档中剥离开 var container = $('#container').detach(); var child1 = '<div>I am Monkey</div>'; var child2 = '<div>Monkey is me</div>'; //将child一、child2插入container中 $(container).append( child1 ) .append( child2 ); //将container从新插入body中 $('body').append( container ); }); </script> </body> </html>
参考资料: jquery中detach()移除元素 http://www.studyofnet.com/news/1225.htmlspa