Blogger Information
Blog 17
fans 0
comment 0
visits 11991
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
jquery DOM 操作
一片叶
Original
686 people have browsed it

jquery中插入节点的四种方法

  • appendTo():  将符合条件的元素追加至appendTo的参数节点内(形成了子元素)

  • prependTo():  将符合条件的元素添加至prependTo的参数节点内的首位(形成了子元素)

  • insertAfter():  将符合条件的元素放置在insertAfter的参数节点之后(形成了一个兄弟元素)

  • insertBefore(): 将符合条件的元素放置在insertBefore的参数节点之前(形成了一个兄弟元素)

  • 注意事项:如果使用eq()索引元素, 则要注意索引会随着位置的变化而变化

  • <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>  
    <title>jquery DOM操作</title>
    </head>
    <body>
    <div style="border:1px solid skyblue;width:300px;">
    <ul style="border:1px solid red;width:200px;">
    <li>第一个标签</li>
    <li>第二个标签</li>
    <li>第三个标签</li>
    <li>第四个标签</li>
    </ul>
    <p>第一段文字</p>
    <p>第二段文字</p>
    <p>第三段文字</p>
    <p>第四段文字</p>
    </div>
    <button id="btn1">appendTo()</button>
    <button id="btn2">prependTo</button>
    <button id="btn3">insertAfter()</button>
    <button id="btn4">insertBefore()</button>
    </body>
    <script>
    $("#btn1").click(function(){
    $("p").eq(0).appendTo($("ul"));  //将第一个p追加到ul标签内,成为ul的子元素,显示的位置是第四个标签后面.
    });
    $("#btn2").click(function(){
    $("p").eq(1).prependTo($("ul"));  //将第二个p放在ul标签内的第一个位置,成为ul的子元素显示位置是第一个标签之前
    });
    $("#btn3").click(function(){
    $("p").eq(3).insertAfter($("ul"));//将第四个p放在ul的后面,成为ul的兄弟元素;
    });
    $("#btn4").click(function(){
    $("p").eq(2).insertBefore($("ul")); //将第三个p放在ul的前面,成文他的兄弟元素
    });
    
    </script>
    </html>
Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!