为什么不能在两个dom元素中追加同一个孩子? [英] Why isn't possible to append a same child in two dom element?

查看:300
本文介绍了为什么不能在两个dom元素中追加同一个孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是注意到我做不到

var d1 = document.createElement('div');
var d2 = document.createElement('div');
var p = document.createElement('p');

d1.appendChild(p); // d1 has p now
d2.appendChild(p); // d2 has p now
// but where is p in d1 ?

有些人会说这是逻辑,但是,当我第一次注意到我认为它是多么冷酷时。

Some would say it's logic, but well, when I first noticed that I thought how uncool it was.

为什么不可能?

推荐答案

DOM 结构。

附加元素时,更改其父元素。

When you append an element, you change its parent.

浏览器中的节点很多不仅仅是P中的文本(实际上该字符串可以共享)。它还具有位置,维度,可见性,接收可能在子元素中触发的事件,将事件传播到其父元素,等等。这里的一切都取决于树中的位置。就像许多CSS选择器一样。想象它在两个地方是相同的元素并没有多大意义,最好将它看作两个节点,可能有一些相同的内容。

A node, in the browser, is much more than just the text inside your P (that string could be shared, in fact). It also has a position, dimensions, a visibility, receives events that could have been fired in child elements, propagate events to its parent, and so on. Everything here depends on the position in the tree. Just like would many CSS selectors. It doesn't make a lot of sense to imagine it's the same element at two places, it's better to think about it as two nodes, with maybe some identical content.

如果你想在两个地方拥有相同的内容,你有克隆它

If you want to have the same content at two places, you have to clone it.

这篇关于为什么不能在两个dom元素中追加同一个孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆