2012-07-31 3 views
0

ID가 없으면 스크립트가 중단됩니다. 왜?누락 된 요소가 스크립트를 중단 함 (getElementById)

the_lis를 어떻게 chache하려면?

<!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

당신은 정말 처음 if 문을 사용하여 the_id 존재 여부 있는지 확인해야합니다는, 다른 하나는 현명한 예외가 발생합니다.

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이며, nullgetElementsByTagName 방법이 없습니다. 이봐.

당신이 당신의 코드를 작성하기 전에 ID가 존재하게, 또는 같은 뭔가를 명시 적으로 확인 하나 : 첫 번째 요소는 null 될 것 the_id 존재하지 않기 때문에

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

. 메서드 getElementsByTagNamenull으로 호출하면 오류가 발생합니다.

0

제 생각에 getElementsByTagName은 배열을 반환합니다. 그러나 그 전에는 the_id가 존재하지 않기 때문에 null이거나 정의되지 않아야하므로 null 인스턴스에서 getElementsByTagName을 호출하려고합니다.

나는 당신이해야 할 노력하고 무엇이든 할 jQuery를 사용 (적용되지 않는) 제안하고 자바 스크립트

+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

+0

나는 서 선생님! 나는 지금까지 JavaScript에 대한 많은 것을 배우고 있으므로, 지금까지의 지식은 약간 희박합니다! – series0ne

+0

괜찮습니다. 토론에 참여하는 것이 매우 유용한 학습 도구입니다. – RobG

관련 문제