[英]javascript document.getElementById(“device”) doesn't work?
Why does alert(p1)
show null
? 为什么
alert(p1)
显示为null
?
http://pastebin.com/VAKwwEge http://pastebin.com/VAKwwEge
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/product.js"></script>
</head>
<body>
Device:<select id="device" name="device" style="width:250px;"> </select> Line:<select id="line" name="line" style="width:250px;"> </select>
</body>
</html>
window.onload = load();
function load() {
var p1 = document.getElementById("device");
var l1 = document.getElementById("line");
alert(p1);
alert(l1);
}
Change your code to this: 将代码更改为此:
function load() {
var p1 = document.getElementById("device");
var l1 = document.getElementById("line");
alert(p1);
alert(l1);
}
window.onload = load;
The assignment to onload needs to be a function reference, not the execution of the function (no parens). 对onload的分配需要是一个函数引用,而不是函数的执行(无括号)。
Somewhat simpler would be using an anonymous function like this: 使用这样的匿名函数会更简单一些:
window.onload = function() {
var p1 = document.getElementById("device");
var l1 = document.getElementById("line");
alert(p1);
alert(l1);
}
You need to change this line: 您需要更改此行:
window.onload = load();
To read the following: 阅读以下内容:
window.onload = load;
Note the difference, the first example will invoke the load()
function, and assign its return value to window.onload
, which of course will be undefined
. 注意区别,第一个示例将调用
load()
函数,并将其返回值分配给window.onload
,该值当然是undefined
。
The second example will assign the function itself to window.onload
, which is what you want, and will alert [object HTMLSelectElement]
(in Firefox anyways). 第二个示例将函数本身分配给所需的
window.onload
,并将警告[object HTMLSelectElement]
(无论如何在Firefox中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.