我可以在javascript中将document.getElementById分配给变量 [英] Can I assign document.getElementById to variable in javascript

查看:135
本文介绍了我可以在javascript中将document.getElementById分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

因此可以将此函数分配给变量。像这样

So this function can be assigned to variable. Like this

var hello = document.getElementById;
console.log(hello('hello')));

<div id="hello">hello</div>

但它发生了像这样的错误:

But It occurred error like this:


未捕获TypeError:非法调用

Uncaught TypeError: Illegal invocation


推荐答案

问题是背景。当你接受函数的引用时,你将函数的上下文丢失到 document 。所以,为了做你想做的事,你需要 bind 上下文:

The issue is context. When you take the reference to the function, you lose the function's context to document. So, in order to do what you are trying to, you need to bind the context:

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

工作示例:

var hello = document.getElementById.bind(document);
console.log(hello('hello'));

<div id="hello">hello</div>

这篇关于我可以在javascript中将document.getElementById分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆