gpt4 book ai didi

JavaScript DOM 编码 - 'undefined' 错误

转载 作者:行者123 更新时间:2023-11-28 21:18:17 26 4
gpt4 key购买 nike

我遇到此错误:

'undefined' is null or not an object'

您能看一下并告诉我吗?在我的编码中,我想要简单的 DOM JavaScript 代码

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

最佳答案

您必须在底部移动代码或在加载正文后调用 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>

关于JavaScript DOM 编码 - 'undefined' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7044253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com