在 JavaScript 中,可以将 document.getElementById 分配给变量吗?

5

我认为document.getElementById是一个函数。

这个函数可以被赋值给一个变量。就像这样

var hello = document.getElementById;
console.log(hello('hello')));
<div id="hello">hello</div>

但是出现了这样的错误:

未捕获的类型错误:非法调用


var hello = document.getElementById('hello'); console.log(hello) - zer00ne
你究竟想要做什么? - StudioTime
该方法必须知道要在哪个“Document”实例上调用它。很可能是document - Oriol
2个回答

8
问题在于上下文。当你引用函数时,你失去了函数对于 document 的上下文。因此,为了达到你所想要的效果,你需要绑定上下文:bind
var hello = document.getElementById.bind(document);

工作示例:

var hello = document.getElementById.bind(document);
console.log(hello('hello'));
<div id="hello">hello</div>


1
::document.getElementById 很好 - Oriol

3
将其作为一个带有表示ID的参数的函数进行封装。

var hello = function(id){
     return document.getElementById(id);
}
console.log( hello('hello')  );
<div id="hello">hello</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接