kha*_*aki 2 javascript document getelementbyid
我认为document.getElementById是一个功能.
因此可以将此函数分配给变量.像这样
var hello = document.getElementById;
console.log(hello('hello')));Run Code Online (Sandbox Code Playgroud)
<div id="hello">hello</div>Run Code Online (Sandbox Code Playgroud)
但它发生了这样的错误:
未捕获的TypeError:非法调用
问题是背景.当您参考该函数时,您将丢失函数的上下文document.所以,为了做你想做的事,你需要bind上下文:
var hello = document.getElementById.bind(document);
Run Code Online (Sandbox Code Playgroud)
工作范例:
var hello = document.getElementById.bind(document);
console.log(hello('hello'));Run Code Online (Sandbox Code Playgroud)
<div id="hello">hello</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3042 次 |
| 最近记录: |