gpt4 book ai didi

javascript - 使用javascript评估表单输入单选按钮

转载 作者:行者123 更新时间:2023-12-03 08:03:50 25 4
gpt4 key购买 nike

我正在设置一个 h2 元素来显示通过表单中的单选按钮回答的问题的分数。当答案正确时,会弹出祝贺消息,但 h1 文本会改变一毫秒,然后返回到显示零。

var h2 = document.querySelector("h2");
var correctAnswers = 0;
h2.textContent = correctAnswers;

function getAnswer(){
var radio = document.querySelector("form");
if (radio[0].checked === true) {
correctAnswers++;
alert("Congrats! That answer is correct!");

}
h2.textContent = correctAnswers;
}

var btn = document.getElementById('btn');

btn.addEventListener("click", getAnswer);

HTML 看起来像这样

<body>
<h1></h1>
<form>

<p>John Resig invented which javascript library?</p>
<input type="radio" name="library" value="jQuery">jQuery
<input type="radio" name="library" value="Lodash">Lodash
<input type="radio" name="library" value="Underscore">Underscore
<input id="btn" type="submit"> </form>

<script src="quiz.js"></script>
</body>

最佳答案

Your page is reloading on submit to avoid that you can use as below
form onsubmit="return false;"
<body>
<h2></h2>
<form onsubmit="return false;">

<p>John Resig invented which javascript library?</p>
<input type="radio" name="library" value="jQuery">jQuery
<input type="radio" name="library" value="Lodash">Lodash
<input type="radio" name="library" value="Underscore">Underscore
<input id="btn" type="submit"> </form>

<script>
var h2 = document.querySelector("h2");
var correctAnswers = 0;
h2.textContent = correctAnswers;

function getAnswer(){
var radio = document.querySelector("form");
if (radio[0].checked === true) {
correctAnswers++;
alert("Congrats! That answer is correct!");

}
h2.textContent = correctAnswers;
}

var btn = document.getElementById('btn');

btn.addEventListener("click", getAnswer);
</script>
</body>

关于javascript - 使用javascript评估表单输入单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34480230/

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