jquery 实践操作:div 动态嵌套(追加) div

此片记录在指定 div 中动态添加 div

  • html():
  • append(): 在被选元素的结尾(但仍在元素内部)插入指定的内容。
    语法: $(selector).append(content);  //其中,参数content是必需的,指定要附加的内容。
    append 能够使用函数给被选元素附加内容,语法为:
    $(selector).append(function(index,html)); //function()是必需的,参数index和html都是可选的。index表示接收选择器的index位置,html表示接收选择器的当前html。
    //示例: 在所选元素之后追加
    <html> 
    <head> 
    <script type="text/javascript" src="/jquery/jquery.js"></script> 
    </head> 
    <body> 
        <p>This is a paragraph.</p> 
        <p>This is another paragraph.</p> 
        <button>在每个 p 元素的结尾添加内容</button> 
        <script type="text/javascript"> 
            $(document).ready(function(){ 
              $("button").click(function(){ 
                $("p").append(" <b>Hello jQuery!</b>"); 
              }); 
            }); 
        </script> 
    </body> 
    </html>    

    运行结果如下:

    This is a paragraph. Hello jQuery!
    This is another paragraph. Hello jQuery!

  • appendTo(): 在被选元素的结尾(但仍在元素的内部)插入指定的内容。但不能使用函数来附加内容。
    语法:$(content).appendto(selector); //参数content是必需的,指定要附加的内容。
    //示例:
    <html> 
    <head> 
    <script type="text/javascript" src="/jquery/jquery.js"></script> 
    
    </head> 
    <body> 
        <p>This is a paragraph.</p> 
        <p>This is another paragraph.</p> 
        <button>在每个 p 元素的结尾添加内容</button>
        <script type="text/javascript"> 
            $(document).ready(function(){ 
              $("button").click(function(){ 
                    $("<b> Hello jQuery!</b>").appendTo("p"); 
              }); 
            }); 
        </script>  
    </body> 
    </html>
    运行结果如下:
    
    This is a paragraph. Hello jQuery!
    This is another paragraph. Hello jQuery!
  • 在指定DIV下的第二个P后面增加元素

    <div id="divId">
        <p class="c1">我是第1个</p>
        <p class="c2">我是第2个</p>
        <p class="c3">我是第3个</p>
        <p class="c4">我是第4个</p>
    </div>
    
    <script type="text/javascript">
        var insertHtml='<div>我是插入的元素。</div>'
        $('#divId').find('p').eq(1).after(insertHtml);
    </script>
总结: 动态追加、删除 div 
1. 最好每个div(or其他元素)都有一个识别标志,例如 id;  //eg: <input id='inputPropertyName" + filterNum + "' value='MetricName' />  //动态的filterNum-不一样的id
2. 一般 div 增,删,改,查 功能尽量全部满足;
3. 代码精简--传参,给值的尽量写成统一函数,使用时传参即可;
原文地址:https://www.cnblogs.com/ostrich-sunshine/p/8027007.html