Javascript CloneNode a problem in IE below

2010-07-11  来源:本站原创  分类:Web  人气:191 

CloneNode we all used this method, this method is very good, efficiency is also high recommended. Recently the use of it, discovered a hidden problem more deeply, and we enjoy what. Unlike clone select this more famous, look at the code:

<style type='text/css'>
        input.focus{border:1px solid red; background-color:yellow;}
</style>
<input type="text" name="testinput" check="num" />
<script type="text/javascript">
     var originalInput = $('myinput');
         $E.on(input,'focus',function(){$D.addClass(this,'focus');});
         $E.on(input,'blur',function(){$D.removeClass(this,'focus');});
         var clonedInput = originalInput.cloneNode(true);//deep copy
         clonedInput.removeAttribute('id');//remove id
         document.body.appendChild(clonedInput);
</script>

Note: $, $ D, $ E is in the YUI library, etc. Some of the above methods of packaging, writing and note here only for convenience.

Well, run the program, a strange question arises, clonedInput the focus event actually triggered originalInput the focus event! ! ! (Note: there is this phenomenon only in IE, FF, under normal, others did not test). Some people might think that this is the YUI library bug, which I can be very responsible to tell you this is not the YUI library bug, but IE own bug? Bug: feature.
Mozhe the bar, see next MSDN description:

cloneNode Method
    Copies a reference to the object from the document hierarchy.
Syntax
    oClone = object.cloneNode([bCloneChildren])
Parameters
    bCloneChildren      Optional. Boolean that specifies one of the following values:
    FALSE
       Cloned objects do not include childNodes.
    TRUE
       Cloned objects include childNodes.
Return Value
     Returns a reference to the newly created node.
Remarks
     The cloneNode method copies an object, attributes, and, if specified, the childNodes.
     When you refer to the ID of a cloned element, a collection is returned.
    cloneNodedoes not work on an IFRAME directly. You must call cloneNodethrough the
    all collection.

After reading the estimates are very disappointed, not any signs. . .
Another look at the wording again:

<script type="text/javascript">
     var originalInput = $('myinput');
         originalInput.onfocus = function(){$D.addClass(this,'focus');};
         originalInput.onblur = function(){$D.removeClass(this,'focus');};
         var clonedInput = originalInput.cloneNode(true);//deep copy
         clonedInput.removeAttribute('id');//remove id
         document.body.appendChild(clonedInput);
</script>

The wording will not be a problem, event trigger may have been okay.
According to MSDN's explanation, depth copy will copy all child nodes, where the direct write originalInput.onfocus = ..., then the onfucs is considered an attribute of the originalInput (Note: FF is not the case), so you can replicate normally. As for the difference between two kinds of binding events, here is not to explain, in their search bar.

See next case of a problem, the problem lies in the $ E.on (input, 'focus', function () ($ D.addClass (this,' focus');}); of this above. The following is my understanding: see next YUI source code can see this is by adding IE-specific event attachEvent method, binding method does not as a property to deal with input, this approach and focus of this event is bound, I understand it as a reference point to the in it, preserved in memory. When the copy, this method will not be copied, but the focus of this event is copied, or duplicated from the input of focus events point to this method, this method only exists in memory one. However, this method was created for a start, inside this method the context is the input, they have integrated, and can not be changed. Focus in clonedInput trigger event has, indeed triggered binding events, but because of this method which is input, rather than clonedInput, so there are the strange phenomenon.
(Note: The above is just my speculation point of view, I do not know if completely correct, the reader to judge for themselves. Mootools see attached statement)

Well, since we know is that this point does not arise, the solution is simple, as follows:

<script type="text/javascript">
     var originalInput = $('myinput');
         $E.on(input,'focus',function(e){
         $D.addClass($E.getTarget(e),'focus');//use $E.getTarget(e) method to get the correct event obj.
         });
         $E.on(input,'blur',function(e){$D.removeClass($E.getTarget(e),'focus');});
         var clonedInput = originalInput.cloneNode(true);//deep copy
         clonedInput.removeAttribute('id');//remove id
         document.body.appendChild(clonedInput);
</script>

Well, everything is OK.

Finally, please refer to the following mootools of Daniel Steigerwald (mootools has its own clone method) to say:
https: / / mootools.lighthouseapp.com/projects/2706/tickets/332-moo-element-clone-patch-fix

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();// The key is the 2-step
                    cloned.mergeAttributes(shallowClone);// The key is the 2-step
                }
                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 previously used this method, which has not discovered that there are so many subtleties, and shows how to write code base is not an easy thing ah for them to express my sincere admiration!

相关文章
  • Javascript CloneNode a problem in IE below 2010-07-11

    CloneNode we all used this method, this method is very good, efficiency is also high recommended. Recently the use of it, discovered a hidden problem more deeply, and we enjoy what. Unlike clone select this more famous, look at the code: <style type=

  • Javascript memory leak problem 2009-07-03

    Memory leak, that is, memory can not be configured correctly, the memory can not be timely and effective recovery, he will lead the implementation of efficient procedures for the implementation of the failure of even lower. The field in the browser,

  • JavaScript parsing parameters problem!!!! 2010-07-12

    1, see the time is too sloppy. I asked some people up on what the results of a json or something. Json fact and not tied. To the question: Encountered this problem in other people's pages when climbing experience. A node: <img src='about:blank'"th

  • javascript pop-up window problem 2010-07-21

    1. Silent refresh the page we have found that some web pages to refresh when a prompt window will pop up, click "OK" will refresh. However, some pages will not be prompted, not pop-up prompt window, directly refreshed. If the page does not form,

  • Hyperlink in the javascript: void (0) problem 2010-08-17

    Doing a page, a link to click if they want to do nothing after, or completion of other things to respond to clicks, you can set its properties href = "#", but there is quite a problem is that when a scroll bar when the page , when clicked, will

  • JavaScript floating point problem analysis and solution 2010-10-16

    JavaScript is only one numeric type Number, but also in the Javascript all of the figures are based on IEEE-754 ( http://zh.wikipedia.org/zh-cn/IEEE_754 ) expressed in standard format. JavaScript floating point precision problem is not unique, becaus

  • javascript Chinese garbage problem 2009-08-06

    Today is to the company's third week, or in the framework of the tired look! ! ! However, to continue its efforts Oh HA HA Problems inside the framework of the JavaScript comments become garbled in Chinese Solution: Windows-> preferences-> MyEclipse

  • JavaScript method overload problem 2010-10-13

    JavaScript's method does not allow duplicate names, the form can not be achieved Java method overloading, but there is heavy demand by the method in which, by determining the parameter type, number of parameters (presence), the parameters of the orde

  • javascript cloneNode()方法的使用 2015-03-14

    控件cloneNode()方法的使用 实例代码. 控件cloneNode()方法的使用 姓名 性别 年龄 1. 请选择性别 男 女 [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

  • javascript inherited a problem when 2009-08-15

    prototype is the object of property, inheritance issues that may arise Shape = function () () Shape.prototype = ( area: [1,2,3] ) var Rectange = function () ( this.area.push (4); ) Rectange.prototype = new Shape (); var Square = function () ( ) Squar

  • javascript cross-domain access problem 2010-05-07

    1, for example in the browser to access the following address: http://localhost:8000/webUI/index.html 2, and in the index.html through jquery Ajax requests are as follows: $. Ajax (( url: 'http://127.0.0.1:8000/?cmd=login, type: "GET", dataType:

  • Javascript memory leak on the collation of draft issues 2009-07-03

    Wrote a long time a small javascript function modules, has never been concerned about the issue of memory leaks. Remember to write C + + procedures, memory leak is a serious issue, I think it is time for a look. Find the articles online, Mark look. O

  • What is JavaScript? You how to implement it 2010-08-30

    What is JavaScript? How do you implement it? JavaScript is a text-based programming language, is executed without any prior conversion. Other programming languages such as Java and C + + compiler needs to be carried out in order to become executable

  • The Seven Rules of Unobtrusive JavaScript 2010-12-30

    1. Do not make any assumptions (JavaScript is an unreliable assistant) * Do not assume that JavaScript is available, you'd better think it is probably not available, and not directly dependent on it. * You have been tested in a number of methods and

  • Javascript object-oriented features 2011-01-08

    JavaScript supports object-oriented ~~~~~~~~~~~~~~~~~~ Few object-oriented features of JavaScript for system analysis. I hope that the next words you understand that the language at least well known of the side. 1. JavaScript types in the -------- Wh

  • DWR-related elements 2009-06-14

    DWR collection converter using Abstract <convert converter="collection" match="java.util.Collection"/> From the Java Object -> Javascript Object little problem, there is reference example is the Java function returns a Collect

  • Firebug installation method 2009-08-14

    the development of a firefox plug-in, Troubleshooting Javascript CSS DOM problem, check the flow of time for pages to load Net, all inside glimpses of speed to find the problem. So many good things to it, attached to a diagram: '700 ') This.width = '

  • Conventional circular reference memory leaks and memory leaks Closure 2010-06-01

    To learn javascript memory leak problem, we must first understand that the GC principles of javascript. I remember the original books in the rhino "JavaScript: The Definitive Guide" in the seen, IE uses the GC algorithm is counter, it only hit w

  • JS out of memory, debugging tools introduced 2010-06-07

    javascript memory leak problem has not been everyone's attention because of the impact of user performance is not too realistic, perhaps developed rapidly in recent years memory. Script memory leak will not be much longer impact. Of course, as the fr

  • PHP Code Complete used 2010-09-03

    PHP code used 1, database code to connect MYSQL <? Php $ Connec = mysql_connect ("localhost", "root", "root") or die ("can not connect to database server:". Mysql_error ()); mysql_select_db ("liuyanben"