javascript - DIV 节点怎么会是 "detached",有什么用?

标签 javascript jquery dom

本文创建了一个分离的 Div 节点: http://www.bennadel.com/blog/1008-jQuery-empty-Kills-Event-Binding-On-Persistent-Nodes.htm

我不明白:我认为 DOM 拥有每个节点。那么您将如何附加到 DOM?

最后但同样重要的是,分离节点的目的是什么?

最佳答案

我不确定你期望哪个答案,所以这里有一些想法:

I thought that DOM owns every nodes.

文档 拥有每个节点。每个节点都有一个 ownerDocument [MDN]属性(property)。

来自specification :

The Document interface represents the entire HTML or XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data.

Since elements, text nodes, comments, processing instructions, etc. cannot exist outside the context of a Document, the Document interface also contains the factory methods needed to create these objects. The Node objects created have a ownerDocument attribute which associates them with the Document within whose context they were created.


How would you attach to DOM then?

插入新节点的方式有很多种,比如appendChild [docs]insertBefore [docs] .


Last but not least what would be the purpose of having detached node ?

一个优点是您可以离线构建复杂的子树,这样浏览器就不必在您每次插入节点时都重新计算布局。

有时它对于解析 HTML 字符串也很有用。通过创建一个空的、分离的 div 并将 HTML 字符串分配给 innerHTML,您可以轻松地解析和处理 HTML 字符串。

唯一需要注意的是 document.getElementById 无法找到不属于树的节点。


在这方面也很有趣的可能是对 Node.parentNode 属性的解释。毕竟,没有父节点的 Node 不是树的一部分:

The parent of this node. All nodes, except Attr, Document, DocumentFragment, Entity, and Notation may have a parent. However, if a node has just been created and not yet added to the tree, or if it has been removed from the tree, this is null.

关于javascript - DIV 节点怎么会是 "detached",有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8694445/

相关文章:

javascript - 无法将数据 append 到 Div 并重定向页面

javascript - 单击链接时取消选中复选框

javascript - 将等式转换为 CSS calc 导致 "invalid property value"

javascript - 谷歌地图中工具提示的背景颜色变化

javascript - 使用 jQuery 和 CSS 根据另一个 div 的文本更改背景颜色

ajax - 将 jquery slider 绑定(bind)到 dom

jquery - 如何创建 DOM 节点作为对象?

c# - 如何使用 sdocvw.dll 在 c# 中监听任何 DOM 事件

javascript - 推开然后恢复 “mouse move” 上的点位置

javascript - 社交媒体图标之间的间距