使用单选按钮的输入计算分数

Calculate score using input from radio buttons

本文关键字:计算 输入 单选按钮      更新时间:2023-09-26

我想使用函数 check() 并通过它传递单选按钮的名称,以便注册所有按钮的输入。 但似乎我无法使用 OnClick HTML 属性传递任何东西。我打算添加更多问题,所以我需要一种方法来轻松地对所有问题使用 check() 函数。

<div class="questionCard" id="q1">
                <p>Each problem consists of three statements. Based on the first two statements, the third statement may be true, false, or uncertain.</br></br>
                1.</br>
                Tanya is older than Eric.</br>
                Cliff is older than Tanya.</br>
                Eric is older than Cliff.</br>
                If the first two statements are true, the third statement is</p>
                <input type="radio" name="a1" onclick="check(a1)" value="true"/>True
                <input type="radio" name="a1" onclick="check(a1)" value="false"/>False
                <input type="radio" name="a1" onclick="check(a1)" value="uncertain"/>Uncertain
            </div>
            <div class="questionCard" id="q2">
                <p>
                2.</br>
                Blueberries cost more than strawberries.</br>
                Blueberries cost less than raspberries.</br>
                Raspberries cost more than strawberries and blueberries.</br>
                If the first two statements are true, the third statement is</p>
                <input type="radio" name="a2" value="true"/>True
                <input type="radio" name="a2" value="false"/>False
                <input type="radio" name="a2" value="uncertain"/>Uncertain
            </div>
            <div class="questionCard" id="q3">
                <p>
                3.</br>
                All the trees in the park are flowering trees.</br>
                Some of the trees in the park are dogwoods.</br>
                All dogwoods in the park are flowering trees.</br>
                If the first two statements are true, the third statement is</p>
                <input type="radio" name="a3" value="true"/>True
                <input type="radio" name="a3" value="false"/>False
                <input type="radio" name="a3" value="uncertain"/>Uncertain
            </div>

这是Javascrpt。

var score=0;
function check (name) {
    var methods = document.getElementsByName('name');
    for (var i=0; i<methods.length; i++) {
         if (methods[i].checked == true) {
             score +=1;
             alert(score);
            }
   }
}

在 HTML 中,您尝试传递变量a1而不是字符串"a1" 在你放置在事件中的check()函数onclick所以你应该替换:

onclick="check(a1)"

跟:

onclick="check('a1')"

在你的 JavaScript 中,你总是在寻找带有 name="name" 的元素,所以你应该替换:

var methods = document.getElementsByName('name');

跟:

var methods = document.getElementsByName(name);