0

为什么这会在例如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>
4

1 回答 1

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>
于 2013-06-21T23:34:58.433 回答