本节书摘来自异步社区《jQuery、jQuery UI及jQuery Mobile技巧与示例》一书中的第3章,第3.10节,作者:【荷】Adriaan de Jonge , 【美】Phil Dutson著,更多章节内容可以访问云栖社区“异步社区”公众号查看
可以把元素从HTML树上分离(detach)出来,然后把它重新添加(reattach)到不同的位置。代码清单3-10演示了如何做到这一点。
代码清单3-10 使用appendTo()和detach()在DOM树中移动元素
00 <!DOCTYPE html> 01 02 <html lang="en"> 03 <head> 04 <title>The attach() and detach() function</title> 05 <style> 06 /* 请将下列代码移至一个外部的 07 .css文件 */ 08 .detaching button.attach { 09 display: none; 10 } 11 .attaching button.detach { 12 display: none; 13 } 14 </style> 15 </head> 16 <body class="detaching"> 17 18 <div> 19 <button class="attach">Attach</button> 20 <button class="detach">Detach</button> 21 <span>First element</span> 22 </div> 23 <div> 24 <button class="attach">Attach</button> 25 <button class="detach">Detach</button> 26 <span>Second element</span> 27 </div> 28 <div> 29 <button class="attach">Attach</button> 30 <button class="detach">Detach</button> 31 <span>Third element</span> 32 </div> 33 <div> 34 <button class="attach">Attach</button> 35 <button class="detach">Detach</button> 36 <span>Fourth element</span> 37 </div> 38 <div> 39 <button class="attach">Attach</button> 40 <button class="detach">Detach</button> 41 <span>Fifth element</span> 42 </div> 43 44 45 <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 46 47 <script> 48 // 请将下列代码移至一个外部的.js文件中 49 $(document).ready(function() { 50 var el; 51 52 $('.detach').click(function() { 53 el = $(this).parent().children('span:first').remove(); 54 $('body').removeClass('detaching').addClass('attaching'); 55 }); 56 $('.attach').click(function() { 57 el.appendTo($(this).parent()); 58 $('body').removeClass('attaching').addClass('detaching'); 59 }); 60 61 }); 62 </script> 63 </body> 64 </html>分离元素除了把元素移至不同的位置外,还有一个重要的使用场景是需要对HTML树执行大量的操作。先分离元素再操作它时需要的系统资源较少。值得注意的是,detach()函数会保留所有和分离元素关联的jQuery数据(包括函数和对象)。这在把元素重新添加到DOM时尤其有用,这也是上面的技巧能够移除内容然后重新添加到文档中而没有影响的原因。
相关资源:jQuery.ui.1.7.2中文文档