Set document.getElementById to variable

前端 未结 5 686
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 00:41

The following works:

    $ = document.form;
    x = $.name.value;

This doesn\'t:

    $ = document.getElementById;
    x = $         


        
5条回答
  •  青春惊慌失措
    2020-12-02 00:58

    getElementById is a method of the HTMLDocument prototype (of which document is an instance). So, calling the function in global context you will surely get an "Wrong this Error" or something.

    You may use

    var $ = document.getElementById.bind(document);
    

    but

    function $(id) { return document.getElementById(id); }
    

    is also OK and maybe better to understand.

提交回复
热议问题