Onsubmit 函数刷新页面
Onsubmit function refreshes page
非常基本的代码,我无法开始工作。 onsubmit 函数被调用,但页面刷新回其原始形式,就好像它执行但随后重新启动 HTML。 console.log 闪烁,然后消失,就好像我们重新启动了页面一样。
我已经注释掉了“return false”,因为这似乎没有什么不同。
我犯了什么愚蠢的错误?提前致谢。
<form method="POST" style="display: inline" onsubmit="validateAnswer()">
<label for="answer" >Secret Word</label>
<input id="answer" name="answer" size="15" type="text" />
<input type="submit" value="Submit">
</form>
<br>
<h5 id="answerText"></h3>
<script>
function validateAnswer() {
var y = document.getElementById("answer").value;
console.log("y: " + y);
if ( y == "YOU" || y == "You" || y == "you" ){
document.getElementById("answerText").innerHTML = "Correct!";
// return false;
} else {
document.getElementById("answerText").innerHTML = "Sorry, that's not correct";
// return false;
}
}
</script>
您错过了 action 和 event.preventDefault(); 以阻止发送表单
function validateAnswer(event) {
var y = document.getElementById("answer").value;
console.log("y: " + y);
if ( y == "YOU" || y == "You" || y == "you" ){
document.getElementById("answerText").innerHTML = "Correct!";
// return false;
} else {
document.getElementById("answerText").innerHTML = "Sorry, that's not correct";
event.preventDefault();
return false;
}
}
<form method="POST" style="display: inline" action="https://whosebug.com/" onsubmit="validateAnswer(event)">
<label for="answer" >Secret Word</label>
<input id="answer" name="answer" size="15" type="text" />
<input type="submit" value="Submit">
</form>
<br>
<h5 id="answerText"></h3>
非常基本的代码,我无法开始工作。 onsubmit 函数被调用,但页面刷新回其原始形式,就好像它执行但随后重新启动 HTML。 console.log 闪烁,然后消失,就好像我们重新启动了页面一样。
我已经注释掉了“return false”,因为这似乎没有什么不同。
我犯了什么愚蠢的错误?提前致谢。
<form method="POST" style="display: inline" onsubmit="validateAnswer()">
<label for="answer" >Secret Word</label>
<input id="answer" name="answer" size="15" type="text" />
<input type="submit" value="Submit">
</form>
<br>
<h5 id="answerText"></h3>
<script>
function validateAnswer() {
var y = document.getElementById("answer").value;
console.log("y: " + y);
if ( y == "YOU" || y == "You" || y == "you" ){
document.getElementById("answerText").innerHTML = "Correct!";
// return false;
} else {
document.getElementById("answerText").innerHTML = "Sorry, that's not correct";
// return false;
}
}
</script>
您错过了 action 和 event.preventDefault(); 以阻止发送表单
function validateAnswer(event) {
var y = document.getElementById("answer").value;
console.log("y: " + y);
if ( y == "YOU" || y == "You" || y == "you" ){
document.getElementById("answerText").innerHTML = "Correct!";
// return false;
} else {
document.getElementById("answerText").innerHTML = "Sorry, that's not correct";
event.preventDefault();
return false;
}
}
<form method="POST" style="display: inline" action="https://whosebug.com/" onsubmit="validateAnswer(event)">
<label for="answer" >Secret Word</label>
<input id="answer" name="answer" size="15" type="text" />
<input type="submit" value="Submit">
</form>
<br>
<h5 id="answerText"></h3>