jquery 向html添加元素append prepend before after

原始html文件如下

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <title>hello world</title>
        <script src="../js/jquery.min.js"></script>
        <script>
            $(document).ready(
                function()
                {
                    $("#append").click(
                        function()
                        {
                            $("#second").append("<p>append</p>");
                        }
                    );
                    $("#prepend").click(
                        function()
                        {
                            $("#second").prepend("<p>prepend</p>");
                        }
                    );
                    $("#before").click(
                        function()
                        {
                            $("#second").before("<p>before</p>");
                        }
                    );
                    $("#after").click(
                        function()
                        {
                            $("#second").after("<p>after</p>");
                        }
                    );
                }
            );// end document.ready()
        </script>
    </head>
    <body>
    
        <button id="append">append</button>
        <button id="prepend">prepend</button>
        <button id="before">before</button>
        <button id="after">after</button>
        
        <p>first line</p>
        <p id="second">second line</p>
        <p>third line</p>
    
    </body>
</html>

依次点击append,prepend,before,after后查看源代码如下

 1 <!DOCTYPE html>
 2 <html lang="zh-CN">
 3 <head>
 4 <body>
 5 <button id="append">append</button>
 6 <button id="prepend">prepend</button>
 7 <button id="before">before</button>
 8 <button id="after">after</button>
 9 <p>first line</p>
10 <p>before</p>
11 <p id="second">
12 <p>prepend</p>
13 second line
14 <p>append</p>
15 </p>
16 <p>after</p>
17 <p>third line</p>
18 </body>
19 </html>

可知:

  1. append添加新元素到当前元素结束标签的前面(新元素在当前元素内)
  2. prepend添加新元素到当前元素开始标签的后面(新元素在当前元素内)
  3. before添加新元素到当前元素起始标签的前面(新元素在当前元素前面)
  4. after添加新元素到当前元素结束标签的后面(新元素在当前元素后面)
原文地址:https://www.cnblogs.com/qiudeqing/p/2797567.html