《jQuery、jQuery UI及jQuery Mobile技巧与示例》——3.14 技巧:移除元素

    xiaoxiao2024-04-06  136

    本节书摘来自异步社区《jQuery、jQuery UI及jQuery Mobile技巧与示例》一书中的第3章,第3.14节,作者:【荷】Adriaan de Jonge , 【美】Phil Dutson著,更多章节内容可以访问云栖社区“异步社区”公众号查看

    3.14 技巧:移除元素

    当使用detach()移除元素后,它会从屏幕和文档树中消失,但它还保存在内存中。代码清单3-14演示使用remove()和empty()函数把元素从文档和内存中删除。remove()函数会返回被移除的元素,所以可以把它们用变量保存起来,再将它们重新插入到页面中。请记住,当用remove()函数来这么做的时候,所有的jQuery数据和事件信息都会丢失。

    代码清单3-14 演示remove()和empty()之间的区别

    00 <!DOCTYPE html> 01 02 <html lang="en"> 03 <head> 04  <title>The remove() and empty() function</title> 05  <style> 06  /* 请将下列代码移至一个外部的 07    .css文件 */ 08  p { 09   border: 1px solid red; 10  } 11  </style> 12 </head> 13 <body> 14 15 <h1>Click on the paragraph to remove</h1> 16 <p id="remove">This text will have a different appearance after 17   clicking it</p> 18 19 <h1>Click on the paragraph to remove the spans</h1> 20 <p id="remove-spans">This text <span id="test">will</span> 21  have <span>a</span> different appearance after 22  <span>clicking</span> it</p> 23 24 <h1>Click on the paragraph to empty</h1> 25 <p id="empty">This text will have a different appearance 26   after clicking it</p> 27 28 <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 29 30 <script> 31 // 请将下列代码移至一个外部的.js文件中 32 $(document).ready(function() { 33  34  $('p#remove').click(function() { 35   $(this).remove(); 36  }); 37 38  $('p#remove-spans').click(function() { 39   $(this).children('span').remove(); 40  41   // 无效: 42   //$(this).remove('span'); 43  44   // 移除元素自身: 45   //$(this).remove(':has(span)'); 46  }); 47 48  $('p#empty').click(function() { 49   $(this).empty(); 50  }); 51  52 }); 53 </script> 54 </body> 55 </html>

    第35行的remove()函数移除了整个段落元素。在第39行,remove()移除了段落中的span元素。和remove()函数的其他示例类似,也可以使用$(this).children().remove('span')实现相同的功能。第49行调用empty()时,段落元素依旧存在,但是它的文本内容被移除了。如果段落元素包含了任何子元素,它们也会被删除。请运行上面的代码示例,看一看红色边框的视觉效果。

    相关资源:敏捷开发V1.0.pptx
    最新回复(0)