0

I am a bit new to Javascript, but I am trying to setup a very simple user input/response system. For some reason, I have run into this before where innerHTML was not displaying information given to it. Here is the basic setup of what I am trying to do:

<!DOCTYPE html>
<html>
<head>
    <title>titles are lame</title>
    <link/>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
    <script type="text/javascript" src="script.js"></script>
    <script></script>
</head>
<body>
<div id="wrapper"><div id="text">Test</div>
<br>
<input type='text' id="input"><input type="submit"id="submit" onclick="act()">
<input type="button" value="Button" onclick="act()">

</div>
</body>
</html>

That was the HTML just in case I was missing something simple. Here is the Javascript.

var state = 0;
var inputf = getElementById("input");
var text = getElementById('text');
var input, name, age;

function act(){
input = inputf.content;
switch(state){
    case 0:
        text.innerHTML = "This is supposed to overwrite Test text.";
        break;
    case 1:
        break;
}
}
4

1 回答 1

3

您在脚本的全局范围内调用doing var text = getElementById('text');,这意味着它会在脚本加载后立即发生,可能在页面的其余部分加载之前。因此,您尝试获取的元素可能还不存在。

尝试将这些变量的初始化移动到act().

于 2013-03-21T19:00:02.807 回答