克隆 DOM 元素后丢失对它们的引用
使用 MooTools,当 DOM 准备就绪时,我会在变量中缓存一些 DOM 元素,如下所示:
var mc = $('main-content'),
bg = $('bg'),
arrows = $$('arrows');
bg
和 arrows
都位于 mc
DOM 元素。我想克隆 mc
节点,对其执行一些操作,然后将克隆插入到 DOM 中:
function updateDOM (parent) {
var parentID = parent.id,
oldNode = document.getElementById(parentID),
clone = oldNode.cloneNode(true);
// work with clone
oldNode.parentNode.replaceChild(clone, oldNode);
}
当我运行 updateDOM(mc)
时,我发现任何其他后续操作会更改 mc
、bg
或 arrows
的函数不起作用。当我执行 console.log() 元素时,它们会显示出来,但它们不会反映自初始化以来所做的任何更改。
考虑到我正在克隆该元素,mc
不再引用 div#main-content
对我来说是有意义的。 updateDOM()
是一个可以被任何元素使用的函数。我是否真的需要硬编码一种方法来重新实例化我缓存的每个变量,或者是否有更动态的方法来执行此操作?
Using MooTools, I'm caching some DOM elements in variables when the DOM is ready, like so:
var mc = $('main-content'),
bg = $('bg'),
arrows = $('arrows');
Both bg
and arrows
are located within the mc
DOM element. I want to clone the mc
node, perform some operations on it and then insert the clone into the DOM:
function updateDOM (parent) {
var parentID = parent.id,
oldNode = document.getElementById(parentID),
clone = oldNode.cloneNode(true);
// work with clone
oldNode.parentNode.replaceChild(clone, oldNode);
}
When I run updateDOM(mc)
, I find that any other subsequent functions that would change mc
, bg
, or arrows
don't work. When I do console.log() the elements, they show up, but they don't reflect any of the changes that have been made since their initialization.
Considering that I'm cloning the element, it makes sense to me that mc
no longer references div#main-content
. updateDOM()
is a function that could be used by any element. Do I really need to hard code a way to re-instantiate each variables that I cache or is there a more dynamic way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许我很厚,但在我看来,上面的函数传递了一个分配给parent的元素引用。然后,它使用 getElementById(parent.id) 获取对同一元素的引用,然后克隆它。这与以下有何不同:
Maybe I'm thick, but it seems to me that the above function is passed an element reference that is assigned to parent. It then uses
getElementById(parent.id)
to get a reference to the same element, then clone it. How is this different to:更改
updateDOM
以返回新的克隆节点,只需更改对updateDOM
的调用即可重新分配变量。Change
updateDOM
to return the new, cloned node, and just change your calls toupdateDOM
to also reassign the variable.