我有這個網頁,我必須使用很多document.getElementById
的。因爲我懶,我想節省幾個字節的通過分配document.getElementById
爲較短的變量:爲什麼將一個函數(屬於一個對象)分配給一個變量的行爲是這樣的?
var geid = document.getElementById;
然而,這並沒有爲我打算工作。它給了我下面的錯誤:
Uncaught TypeError: Illegal invocation
考慮下面的代碼片段這說明我的問題:
var foo = document.getElementById('foo');
console.log(foo); // outputs: '<div id="foo">Foo</div>'
var geid = document.getElementById;
var foo_geid = geid('foo'); // Aaaaaargh! Uncaught TypeError: Illegal invocation
console.log(foo_geid);
<div id="foo">Foo</div>
那我做錯了嗎?爲什麼我不能做我做的事?
我檢查了「How does the "this" keyword work?」,因爲我有一個預感,this
必須做所有這一切。 (對我來說,感覺像getElementById
得到某種方式detached from document
object)。但我無法真正指出和闡明問題。誰能幫我?
重複的[https://stackoverflow.com/questions/41757990/can -i-assign-document-getelementbyid-to-variable-in-javascript](https://stackoverflow.com/questions/41757990/can-i-assign-document-getelementbyid-to-variable-in-javascript) –
也許你應該考慮使用谷歌搜索錯誤信息。 [這似乎解釋了這個問題](https://stackoverflow.com/questions/9677985/uncaught-typeerror-illegal-invocation-in-chrome) – musefan
你必須將文件綁定到它 –