關於jQuery的append方法不能多次添加同一個DOM元素的解決方法


 資料來自:https://segmentfault.com/q/1010000007677851?_ea=1419689

  append()方法在jQuery中是使用appendChild()實現的,實現原理如下代碼:

1   append: function() {
2         return this.domManip( arguments, function( elem ) {
3             if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
4                 var target = manipulationTarget( this, elem );
5                 target.appendChild( elem );
6             }
7         });
8     }

  框架中是通過appendChild來操作dom的,appendChild的作用是什么呢?請看w3c解答,它里面也提到可以將元素從一個元素移動到另一個元素,說白了,就是剪切的意思。因此你后面寫的不是不起作用,而是在原地移動,因為就一個對象,你再怎么寫也是一個。

  解決方法:

  1、將這個DOM元素寫進append()中:

  像這樣:

$("xxx").append( " <p class='xxx'>·····</p> " );

 

  2、使用克隆方法:

$("xxx").append($("td").clone());

 

  clone()方法甚至可以復制事件處理程序

  關於jQuery的clone()方法詳情見:http://www.runoob.com/jquery/html-clone.html


免責聲明!

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



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