2011-04-22 33 views
3

這應該是很簡單的...但它不是...>。 <Javascript TypeError:表達式的結果不是一個對象

var x = document.getElementById('x'); 
function snooze() 
{ 
x.style.height = '10px'; 
} 

在執行時,我得到的錯誤是:

TypeError: Result of expression 'x' [null] is not an object.

編輯:擡起頭,它的工作原理當我把函數內部的VAR聲明。我不明白... :-(

function snooze() 
{ 
var x = document.getElementById('x'); 
x.style.height = '10px'; 
} 

回答

12

或者:。

  1. 還有就是頁面上沒有與元素id="x"
  2. 加載文檔之前的代碼運行

如果有id="x"的元素存在,嘗試:

window.onload = function() { 
    // your code in here 
}; 
+1

O .. Om ... Omg ... OQWUGOUB! 我不能相信在頁面末尾調用腳本之前我沒有想到......你先生(或者夫人,無論你喜歡什麼),應該得到一枚獎牌...... – Abhishek 2011-04-22 09:48:46

+0

'window.onload '在頁面加載週期中非常非常晚(在所有外部資源(如圖像和此類負載)之後)。 *有時*這就是你想要的,但很少。爲了更早地運行它,只需將'script'元素放在'body'元素的最後。更多[here](http://developer.yahoo.com/performance/rules.html)和[here](http://groups.google.com/group/closure-library-discuss/browse_thread/thread/1beecbb5d6afcb41) 。 – 2011-04-22 09:54:18

+0

他/她已經在這裏獲得41枚獎牌! http://stackoverflow.com/users/405143/box9?tab=stats – KooiInc 2011-04-22 09:55:57

相關問題