除了在Internet Explorer中,getElementById返回null

时间:2015-11-02 10:54:21

标签: javascript html

我的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>

谢谢!

5 个答案:

答案 0 :(得分:6)

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

这是一个&#39;功能&#39; IE浏览器他们对getElementById的实现最初会搜索具有给定id属性的元素。如果未找到,则会按name属性搜索元素。

如果您想按名称查找元素,请改用getElementsByName()方法。

答案 1 :(得分:2)

没有id subm_myform的表单元素,你有一个名字。将其修复为代码:

{{1}}

答案 2 :(得分:2)

document.getElementById并不是要寻找name。 Internet Explorer不会崩溃,这很奇怪。也许它会尝试找到名称,如果找不到id

在按钮中添加id以解决问题:

<button name="subm_myform" id="subm_myform" type="submit" >Send My Time</button>

答案 3 :(得分:0)

你的

<button name= "subm_myform" type="submit" >Send My Time</button> 

没有ID,试试这个

<button id="subm_myform" name="subm_myform" type="submit" >Send My Time</button> 

答案 4 :(得分:-4)

问题是你想获得一个id,但你没有添加# 另一个问题是你给它一个名字属性,你需要将它设置为id =“subm_myform”

尝试

>>> from itertools import combinations
>>> datas = {'a': 1, 'b': 2, 'c': 3}
>>> list(combinations(datas.keys(), 2))
[('a', 'c'), ('a', 'b'), ('c', 'b')]
>>> index_combination = combinations(datas.keys(), 2)
>>> for indexes in index_combination:
...  print indexes , sum([datas[index] for index in indexes])
...
('a', 'c') 4
('a', 'b') 3
('c', 'b') 5

的document.getElementById( '#subm_myform')style.visibility = '隐藏';