关于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

posted @ 2019-04-23 21:47  梅思德尔车  阅读(2329)  评论(0编辑  收藏  举报