Element accessible with ID

前端 未结 2 1424
耶瑟儿~
耶瑟儿~ 2020-12-04 02:04

I saw a strange behavior. I created a Input.

and tried to access it directly fr

相关标签:
2条回答
  • 2020-12-04 02:29

    To just expand a little on this situation based on a curiosity:

    <html><head>
    <script type="text/javascript">
      var overWrite = "world";
      window.onload = function(){ alert(overWrite); };
    </script></head><body>
    <input id="overWrite" value="hello" />
    </body></html>
    

    Will alert "world". However, with //var overWrite = "world"; (as in with that line commented out), it will alert the [html element]. Note that this is after the page loads so it is persistent and not some sort of temporary assignment.

    Strongly agree that it should not be used due to inconsistency and readability issues.

    EDIT

    Still was curious about this issue and did some more testing. I was curious if access was faster with document.getElementById or by variable reference. Made this test:

    html

    <div id="contentZone"></div>
    

    js

    var startTime = Date.now();
    for( var i = 0; i < 1000; i++){
        for( var n = 0; n < 2000; n++){
            var ni = document.getElementById("contentZone");
        }
    }
    var endTime = Date.now();
    console.log( endTime - startTime );
    
    var aTime = Date.now();
    for( var i = 0; i < 1000; i++){
        for( var n = 0; n < 2000; n++){
            var ni = contentZone;
        }
    }
    var bTime = Date.now();
    console.log( bTime - aTime );
    

    console

    431
    814
    

    Tested on this machine only, but it would seem that using document.getElementById is still faster making this variable access even less desirable.

    0 讨论(0)
  • 2020-12-04 02:30

    Back in the days of 4.0 browsers, Microsoft decided that it would be convenient to create, for every element with an id, a global variable with the same name as the id containing a reference to that element.

    Support for this has appeared in some other browsers (in some rendering modes). This support is not universal so the feature should be avoided.

    0 讨论(0)
提交回复
热议问题