除了在Internet Explorer中,getElementById返回null

Bor*_*rsi 0 html javascript

我的javascript document.getElementById函数有问题.问题是,除Internet Explorer之外的每个浏览器都会收到document.getElementById为null的错误.

例如Firefox:

TypeError:document.getElementById(...)为null

getElementById-Function出现按钮声明之后,因此它不应该是一个问题,该函数不知道ID元素是什么.

这是带有相关代码的脚本的摘录:

<html>
<head>
<title>Timeline</title>
<meta charset="utf-8">
</head>

<body>
<form method="post" id="myform" onsubmit="window.location.reload();">
<input type="hidden" id="client_timestamp" name="client_timestamp" />
<button name= "subm_myform" type="submit" >Send My Time</button>
</form>

<script type="text/javascript">
// ------- where the error occurs ----------------
document.getElementById('subm_myform').style.visibility='hidden';
var mySync = setTimeout( function () {document.getElementById('subm_myform').click()} ,60000);

</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

谢谢!

dee*_*akb 7

因为你正在获取DOM元素id并且看起来你DOM元素没有任何id属性.它应该是<button name= "subm_myform" type="submit" id="subm_myform" >Send My Time</button>.

这是IE的"功能".它们的实现getElementById最初搜索具有给定id属性的元素.如果没有找到,则它按name属性搜索元素.

如果要按名称查找元素,请改用该getElementsByName()方法.