Javascript将无法执行

时间:2013-06-21 23:31:26

标签: javascript

为什么这会起作用,例如http://codepen.io/,而不是当我在我的网络服务器上试用它时?使用wamp。这应该是这样的:http://codepen.io/anon/pen/Ctsvp

<!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>
<title>Test</title>
<style type="text/css">
#text {
width: 540px;
height: 50px;
overflow: hidden;
}

#submit {
display: none;
}
</style>
<script>
var textInput = document.getElementById('text')
, submitButton = document.getElementById('submit');
function checkTextValue() {
if (textInput.value !== '') {
submitButton.style.display = 'block';
} else {
submitButton.style.display = 'none';
}
}
</script>
</head>
<body>

<form action="#" method="post">
<textarea onkeypress="checkTextValue()" onkeyup="checkTextValue()" onchange="checkTextValue()" id="text"></textarea>
<input id="submit" type="submit" value="Submit">
</form>

</body>
</html>

1 个答案:

答案 0 :(得分:4)

您应该等待DOM准备就绪,因此请将代码更改为:

<script>
document.addEventListener('DOMContentLoaded', function() {
    var textInput = document.getElementById('text')
        , submitButton = document.getElementById('submit');
    function checkTextValue() {
        if (textInput.value !== '') {
            submitButton.style.display = 'block';
        } else {
            submitButton.style.display = 'none';
        }
    }
});
</script>