Element accessible with ID

前端 未结 2 1436
耶瑟儿~
耶瑟儿~ 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:

    
    
    
    
    

    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

    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.

提交回复
热议问题