我遇到问题 'undefined'为null或不是对象' 错误。你能来看看,让我知道。在我的编码中,我希望有简单的DOM javascript cod
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script>
init();
function init()
{
getElementByTabIndex("4", "submit")[0].addEventListener("click", Verify, false);
}
function Verify() {
alert('done');
// all verification code will be here...
}
function getElementByTabIndex(index, type, node)
{
if (!node)
{
node = document.getElementsByTagName('body')[0];
}
var a = [];
els = node.getElementsByTagName('*');
for (var i = 0, j = els.length; i < j; i++)
{
if (els[i].tabIndex == index && els[i].type == type)
{
a.push(els[i]);
}
}
return a;
}
</script>
<body>
<input type="email" id="email" /><input type="password" id="pass" /> <label class="Login" for="login"><input value="Log In" tabindex="4" type="submit" id="login"></label>
</body>
</html>
答案 0 :(得分:3)
您必须在底部移动代码或在加载正文后调用init()
。
原因:您尝试在元素存在之前获取它们。
例如:
<head>
<script>
var elm= document.getElementById('id');
//this will be always undefied, as trying to read element even before they exist
</script>
</head>
<body>
<div id='foo'></div>
<script>
var elm= document.getElementById('id');
//this wont be undefined
</script>
</body>
答案 1 :(得分:0)
你打电话:
if (!node) {
node = document.getElementsByTagName('body')[0];
}
但是您的脚本在DOM加载完成之前运行,因此body
标记不存在。
因此node
为undefined
,当您尝试以下操作时,您会收到错误消息:
node.getElementsByTagName('*');
在文档加载时运行init()
,而不是立即运行。
PS。 jsfiddle和Firebug允许我快速调试。
答案 2 :(得分:0)
'body'不可用于javascript。
在dom加载完成后调用你的init方法,如下所示:
window.onload = function (){
init();
}
请注意,为了在浏览器之间进行此操作(如果您计划在计划的Safari扩展之外使用它),您将需要做一些额外的工作。更多信息:http://www.javascriptkit.com/dhtmltutors/domready.shtml