Is there a spec that the id of elements should be made global variable?

前端 未结 5 2111
死守一世寂寞
死守一世寂寞 2020-11-22 05:34

If I have a

in Chrome then in javascript I can do a.stuff() (it\'s like as if a is a global variable).
5条回答
  •  长发绾君心
    2020-11-22 05:53

    Since very early days, IE has created global variables that reference elements by their name or id attribute value. This was never a good idea, but was copied by other browsers in order to be compatible with sites created for IE.

    It is a bad idea and should not be copied or used.

    Edit

    To answer your extra questions:

    ...how will Chrome resolve the ambiguity if i have a div with id a yet have a global variable called a too in my script.

    In IE (which introduced this behaviour) if a global variable is declared with the same name as an element id or name, it will take precedence. However, undeclared globals don't work that way. It shoudn't take much to test that in Chrome (I have but I'm not going to give you the answer).

    And how would an element with id consisting of hyphens ("-"), colons (":"), and periods (".") be translated (ok i know they can be accessed with document.getElementById but how will the browser translate it into the global variable that was representing them)

    Exactly the same as any object property name that is not a valid identifier - square bracket notation (i.e. window['name-or-id']).

提交回复
热议问题