如果ID不存在,脚本将中断。为什么?
如何更改_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>
由于第一个元素不存在,the_id
将是null
。在null
上调用方法getElementsByTagName
将导致错误。
您确实应该检查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');
}
the_id
为null,而null
没有getElementsByTagName
方法。啊。
在编写代码之前,请确保ID存在,或者使用类似的方法明确检查它
var the_lis = the_id ? the_id.getElementsByTagName('li') : [];
根据我的理解,getElementsByTagName返回一个数组。然而,在此之前,_id应该为null或未定义,因为它不存在,因此您试图在null实例上调用getElementsByTagName。
我建议(除非不适用)使用jquery来做你想做的任何事情,并使用firebug来调试你的JavaScript