使用jQuery可以方便的添加新的HTML元素。
下面的方法用于添加HTML元素:

  • append() – 在指定的元素的尾部添加一个新内容。

  • prepend() -在指定的元素里前部添加新内容。

  • after() – 在指定元素后添加新内容

  • before() -在指定元素的前面添加新内容。

乍一看append,prepend 和after,before似乎功能一样,但append,prepend指在选中的元素本身(内部)的前面和后面,而after,before指在选择中的元素的前面和后面。

可以参考下面的append例子:


  1. <!DOCTYPE html>  

  2. <html>  

  3. <head>  

  4.    <meta charset="utf-8">  

  5.    <title>JQuery Demo</title>  

  6.    <script src="scripts/jquery-1.9.1.js"></script>  

  7.    <script>  

  8.        $(document).ready(function () {  

  9.            $("#btn1").click(function () {  

  10.                $("p").append(" <b>Appended text</b>.");  

  11.            });  

  12.  

  13.            $("#btn2").click(function () {  

  14.                $("ol").append("<li>Appended item</li>");  

  15.            });  

  16.        });  

  17.    </script>  

  18. </head>  

  19.  

  20. <body>  

  21.    <p>This is a paragraph.</p>  

  22.    <p>This is another paragraph.</p>  

  23.    <ol>  

  24.        <li>List item 1</li>  

  25.        <li>List item 2</li>  

  26.        <li>List item 3</li>  

  27.    </ol>  

  28.    <button id="btn1">Append text</button>  

  29.    <button id="btn2">Append list items</button>  

  30. </body>  

  31. </html>  



20130309002

prepend示例:


  1. <!DOCTYPE html>  

  2. <html>  

  3. <head>  

  4.    <meta charset="utf-8">  

  5.    <title>JQuery Demo</title>  

  6.    <script src="scripts/jquery-1.9.1.js"></script>  

  7.    <script>  

  8.        $(document).ready(function () {  

  9.            $("#btn1").click(function () {  

  10.                $("p").prepend("<b>Prepended text</b>. ");  

  11.            });  

  12.            $("#btn2").click(function () {  

  13.                $("ol").prepend("<li>Prepended item</li>");  

  14.            });  

  15.        });  

  16.    </script>  

  17. </head>  

  18. <body>  

  19.  

  20.    <p>This is a paragraph.</p>  

  21.    <p>This is another paragraph.</p>  

  22.    <ol>  

  23.        <li>List item 1</li>  

  24.        <li>List item 2</