【问题标题】:Can I assign document.getElementById to variable in javascript [duplicate]我可以将document.getElementById分配给javascript中的变量吗?
【发布时间】:2017-01-20 07:12:57
【问题描述】:

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

所以这个函数可以赋值给变量。像这样

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

但它发生了这样的错误:

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

【问题讨论】:

  • var hello = document.getElementById('hello'); console.log(hello)
  • 你到底想做什么?
  • 该方法必须知道您希望在哪个Document 实例上调用它。可能是document

标签: javascript document getelementbyid


【解决方案1】:

问题在于上下文。当您引用该函数时,您会将函数的上下文丢失到document。所以,为了做你想做的事,你需要bind上下文:

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

工作示例:

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

【讨论】:

  • ::document.getElementById 会很好
【解决方案2】:

将其包装为一个带有代表 ID 的参数的函数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2018-07-30
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多