2012-07-31 107 views
0

如果該標識不存在,則腳本會中斷。爲什麼?缺少元素中斷腳本(getElementById)

如何改變the_lis?

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>test</title> 
</head> 
<body> 
<script> 
window.onload = function(){ 
alert('this will alert'); 
var the_id = document.getElementById('a_id_that_does_not_exist'), 
the_lis = the_id.getElementsByTagName('li'); 
alert('this will NOT alert'); 
} 
</script> 
</body> 
</html> 

回答

0

你真的應該檢查,看看the_id存在與否首先使用if聲明,其他明智的一個異常將被拋出。

window.onload = function(){ 
alert('this will alert'); 
var the_id = document.getElementById('a_id_that_does_not_exist'); 
if (the_id != undefined) 
    the_lis = the_id.getElementsByTagName('li'); 
alert('this will NOT alert'); 
} 
0

the_id是空的,null沒有一個getElementsByTagName方法。咄。

要麼確保ID存在,你寫你的代碼之前,或類似明確地檢查它:

var the_lis = the_id ? the_id.getElementsByTagName('li') : []; 
1

因爲第一元素不存在the_idnull。在null上調用方法getElementsByTagName將導致錯誤。

0

從我的理解,getElementsByTagName返回一個數組。但是在此之前,the_id應該爲空或未定義,因爲它不存在,因此您試圖在空實例上調用getElementsByTagName。

我建議(除非不適用)使用jQuery做任何你正在試圖做的,並使用Firebug調試JavaScript中

+0

[的getElementsByTagName(http://www.w3.org/TR/ 2004/REC-DOM-Level-3-Core-20040407/core.html#ID-A6C9094)返回[NodeList](http://www.w3.org/TR/2004/REC-DOM-Level-3- Core-20040407/core.html#ID-536297177),而不是數組。 jQuery不會幫助,它會默默地失敗。您是否想在發生錯誤的時候立即知道錯誤,或者稍後可能會被其他代碼和處理混淆? – RobG 2012-07-31 01:56:58

+0

我站在正確的先生!目前我正在學習有關JavaScript的知識,所以迄今爲止我的知識都是一個小小的風格! – series0ne 2012-07-31 08:58:13

+0

沒問題,參與討論是非常有用的學習工具。 – RobG 2012-07-31 23:53:31