簡體   English   中英

使用單選按鈕的輸入計算分數

[英]Calculate score using input from radio buttons

我想使用功能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中,您嘗試在放置於onclick事件中的check()函數中傳遞變量a1而不是字符串"a1" ,因此應替換:

onclick="check(a1)"

與:

onclick="check('a1')"

在您的JavaScript中,您總是在尋找name="name"元素,因此您應該替換:

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

與:

var methods = document.getElementsByName(name);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM