我是js的新手。我已经学会了如何创建一个按钮来提交答案。但是我现在想根据用户的回答向用户提供反馈。我已经尝试过了。
<h1>What is your choice?</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Cooperate"> Cooperate
<input type="radio" name="choice" value="Betray"> Betray
</form>
<button onclick="submitAnswer(d1.choice.value)">Submit Answer</button>
<script>
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (val == "Cooperate" ) {
alert('3 points');
} else if {val == "Betray"
alert('0 points');
}
};
</script>
答案 0 :(得分:1)
您的代码中有很多错误, 它应该看起来像这样:
<h1>What is your choice?</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Cooperate"> Cooperate
<input type="radio" name="choice" value="Betray"> Betray
</form>
<button onclick="submitAnswer()">Submit Answer</button>
<script>
var submitAnswer = function() {
var selected = document.querySelector('input[type="radio"]:checked').value;
if (selected)
alert(selected);
}
};
</script>
答案 1 :(得分:1)
尝试
function submitAnswer(){
var selected = document.querySelector('input[type="radio"]:checked').value;
if (selected === "Cooperate"){
alert("3");
}else{
alert("0");
}
}
<h1>What is your choice?</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Cooperate"> Cooperate
<input type="radio" name="choice" value="Betray"> Betray
</form>
<button onclick="submitAnswer()">Submit Answer</button>