gpt4 book ai didi

javascript - 结果输出消失得太快

转载 作者:行者123 更新时间:2023-11-28 00:24:03 26 4
gpt4 key购买 nike

正确或错误的答案输出并很快消失。我如何获得保留在屏幕上的答案。我想将 html 和 js 文件分开。稍后我想做的是将其他短语添加到程序中。

索引.HTML

<head> </head> 
<body>
<form name="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput">
<button id="myBtn">Click here</button>
<div id ="feedback"></div>
</form>
<script src = "phraseScrambler.js"></script>
</body>
</html>

PHRASESCRAMBLER.JS

var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();

function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myBtn").onclick = checkAnswer;}

function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent= "correct";}
else {
elMsg.textContent= "wrong answer";}}

function shuffle(newWords) {
var counter = newWords.length, temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;}
return newWords;}

最佳答案

首先,如果要处理表单提交,请不要​​绑定(bind)点击事件,表单有专门的事件,称为onsubmit。提交表单时,默认浏览器行为是导航到表单操作(在您的情况下重新加载页面)。您需要通过从 onsubmit 处理程序返回 false 来防止这种情况。

更正后的 HTML 为(我为表单提供了一个 id):

<form name="myForm" id="myForm"> ... </form>

然后事件处理将如下所示(注意 checkAnswer 函数中的 return false;):

var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();

function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myForm").onsubmit = checkAnswer;
}

function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent = "correct";
} else {
elMsg.textContent = "wrong answer";
}
return false;
}

function shuffle(newWords) {
var counter = newWords.length,
temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;
}
return newWords;
}
<form name="myForm" id="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput" />
<button>Click here</button>
<div id ="feedback"></div>
</form>

关于javascript - 结果输出消失得太快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29730963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com