首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

Javascript CloneNode 在IE上面的一个有关问题

2012-11-11 
Javascript CloneNode 在IE下面的一个问题相信大家都用过cloneNode这个方法,这个方法很不错,效率也很高,推

Javascript CloneNode 在IE下面的一个问题
相信大家都用过cloneNode这个方法,这个方法很不错,效率也很高,推荐使用。最近在使用它的时候,发现了一个隐藏的比较深的问题,和大家享一下。这个问题不像clone select来得有名气,先看代码:



注:$,$D,$E等是在YUI库上面封装的一些方法,这里只为书写及说明方便。

好了,运行程序,奇怪的问题出现了,clonedInput 的 focus事件竟然触发了 originalInput 的 focus 事件!!!(注:只在IE有此现象,FF下正常,others没测)。有些人可能会认为这是YUI库的bug,这点我可以很负责任的告诉你这不是YUI库的bug,而是IE自己的bug ? bug : feature。
没辙了吧,看下MSDN的说明:

jQuery explanation on IE issue:    IE copies events bound via attachEvent when using cloneNode.    Calling detachEvent on the clone will also remove the events from    the orignal. In order to get around this, we use innerHTML. Unfortunately,    this means some modifications to attributes in IE that are actually only stored as    properties will not be copied (such as the the name attribute on an input).clone: function(contents, keepid) {    var clone = this.cloneNode(!!contents);    function cleanAndFix(cloned, orig) {        cloned.uid = null;        if (!keepid) cloned.removeAttribute('id');        if (Browser.Engine.trident) {            var shallowClone = orig.cloneNode(false);            cloned.clearAttributes();//关键是这2步            cloned.mergeAttributes(shallowClone);//关键是这2步        }        return cloned;    }    if (contents) {        var cEls = clone.getElementsByTagName('*'),                tEls = Browser.Engine.trident && this.getElementsByTagName('*');        for (var i = cEls.length; i--; ) cleanAndFix(cEls[i], tEls && tEls[i]);    }    return $(cleanAndFix(clone, this));}


以前用过mootools的这个方法,一直没发现原来里面有这么多的玄机,可见写代码库是一件多么不容易的事情啊,对他们表示由衷的敬佩!

热点排行