这方面的新手,刚刚开始使用一点JavaScript。我不明白为什么以下内容不能用于渲染。html在那里,但当点击按钮时,我没有收到任何文本。
<!doctype html>
<html>
<head>
<title>Js to Validate Data</title>
</head>
<body>
<h1>Can JS Validate User input?</h1>
<p> Please enter number between 1 and 21:</p>
<input id="nums" type="number">
<button type="button" onclick="chkData()">Verify Entry</button>
<p id="demo"></p>
<script>
function chkData() {
var x, text;
x = document.getElementById("nums").value;
if (isNaN(x) || x<1 || x> 21) {
text = "Invalid Input, try again!";
}
else {
text = "All Ok!";
}
}
</script>
</body>
</html>
您应该对正在发生的事情有点具体。据我所知,您无法看到text
,因为您没有将其添加到html中。选择id为demo
的div,并使用innerText
将文本附加到div。
function chkData() {
var x, text;
x = document.getElementById("nums").value;
if (isNaN(x) || x<1 || x> 21) {
text = "Invalid Input, try again!";
}
else {
text = "All Ok!";
}
document.getElementById('demo').innerText = text;
}
<h1>Can JS Validate User input?</h1>
<p> Please enter number between 1 and 21:</p>
<input id="nums" type="number">
<button type="button" onclick="chkData()">Verify Entry</button>
<p id="demo"></p>