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. 代碼精簡--傳參,給值的盡量寫成統一函數,使用時傳參即可;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM