-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
今天在一个前端开发的群里看到一个群友问了一个问题:我调用 append() 方法添加两遍元素,为什么最后的只有一个子节点?下面贴出他的代码:
var html_temp = $(container.find("#template").html());
container.append(html_temp);
container.append(html_temp);这段代码表面上看,最后应该有两个 html_temp 节点出现在 container 里面,但是实际结果只有一个子节点,这是为什么?如何才能变成添加几次就有几个子节点呢?
问题在于没有理解jQuery .append() 方法的实现原理,其实,当你传入的参数实际本身是一个 dom 的时候,append的作用不过只是移动这个 dom,那么就会出现群友的那种情况,只是移动了两次这个声明的 dom 对象。下面我给出两个解决办法:
1. 传入 html string
var html_temp = container.find("#template").html();
container.append(html_temp);
container.append(html_temp);2. clone dom 对象
var html_temp = $(container.find("#template").html());
container.append(html_temp.clone());
container.append(html_temp.clone());第一种传入字符串,append 方法会转成一个临时 dom 插入,第二种克隆了 dom 之后插入,实际是一个复制后的 dom 对象。
问题难度不大,但要学会看本质。