2017-09-18 100 views
0

我有這個網頁,我必須使用很多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)。但我無法真正指出和闡明問題。誰能幫我?

+0

重複的[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) –

+0

也許你應該考慮使用谷歌搜索錯誤信息。 [這似乎解釋了這個問題](https://stackoverflow.com/questions/9677985/uncaught-typeerror-illegal-invocation-in-chrome) – musefan

+0

你必須將文件綁定到它 –

回答

1

您需要使用的功能:

var d = function(id) 
{ 
    return document.getElementById(id); 
} 

,然後你可以使用它像這樣:

var el = d('someId'); 
+0

我認爲只是因爲他們回答選民認爲不好的問題纔會看到答案,這是很常見的。有點像'你爲什麼回答這個不好的問題,當它是一個重複,應該被關閉'downvote' – musefan

+0

也許。我認爲這些人已經忘記了他們也曾經學過,也許沒有看到重複的問題。一些新人甚至不知道如何問他們需要什麼。我寧願幫助人們,而不是成爲一些精英撻。 – Stuart

+0

@musefan:我可以問一下這個問題是一個*壞*問題。重複?當然。但不好? :) – Krumia

相關問題