it should worth an article specifically for this topic to clone some elements, most of the cases should be fairly straight forward to clone some elements.
However, the complication comes with the internet explorer, where you have the behaviors that, when they occurs in conjuction, result in a very frustrating scenario for handling cloning.
first, when cloning an element, Internet explorer copies over all event handlers onto the cloned element. Additionally, any custom expandos attached to the cloning are also carried over.
while you cannot just clone the element in IE and then remove the attached events or expandos, because ironically doing so will remove the event handlers and others from the original elements as well.
the solution just clone the element, inject it into another element, then read the innerHTML of the element - and convert that back into a DOM node.
while it sounds all good, but is not yet the whole picture, nasty problems still exist in IE, where
- innerHTML /outerHTML (for that matter) of an elemnt does not always relfect to the correct status, if the name attributes of input elements are changed dynamically - the new value isn't represented in the innerHTML.
- XML DOM elemnts does not have innerHTML (we need to look up what is the definition of innerHTML)
/**
*@Comment : this code is not supposed to be used directly, instead it is written here to show you
* the algorithm to do cloning in libraries such as jQuery. In real use case, you may directly use the jQuery libraries
*/
function clone() {
var ret = this.map(function () {
if (!jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this)) {
var clone = this.cloneNode(true),
container = document.createElement("div");
container.appendChild(clone);
return jQuery.clean([container.innerHTML])[0];
} else {
return this.cloneNode(true);
}
});
var clone = ret.find("*").andSelf().each(function () {
if (this[expando] !== undefined) this[expando] = null;
});
return ret;
}
本文深入探讨了在Internet Explorer浏览器中进行元素克隆时遇到的挑战,特别是事件处理器和自定义扩展的复制问题。提出了一种通过复制元素到另一个元素,读取innerHTML,再转换为DOM节点的方法来解决此问题。同时讨论了innerHTML/outerHTML在动态名称属性下可能不反映实际状态的情况,并提供了一个最终解决方案,即序列化innerHTML,提取为DOM节点,然后针对未传递的属性进行补丁处理。

被折叠的 条评论
为什么被折叠?



