为什么我要问的价格不变?

时间:2018-06-27 19:45:03

标签: javascript jquery input radio-button

HTML:
<p id="Q1">1) Who is the chief justice of the Supreme Court? 

<input type="radio" name="CJ" value="C" class ="correct1">John Roberts
 <input type="radio" name="CJ" value="F" class ="correct1"> Neil Goursuch 
 <input type="radio" name="CJ" value="F" class ="correct1"> Ruth Bayder 
Ginsburg</p>

 <button class="btn btn-danger btn-lg">Done!</button>

        </div>

        <div id="results">

            <p>Correct Answers:<span id="CA"></span></p>

            <p>Incorrect Answers:<span id="IA"></span></p>

            <div id="P/F"></div>
        </div>

Javascript:

        var correctAnswer = 0;

        var wrongAnswer = 0;

        var unAnswered = 0;

        var answer1 = $( ".correct1" ).val();

    $("button").on("click", function(){
        console.log(answer1);
        if(answer1 == "C"){

            correctAnswer++;
            $("#CA").html(correctAnswer);
            console.log(correctAnswer);

        }
        else if (answer1 == "F"){

            $("#IA").html(wrongAnswer);
            wrongAnswer++;
            console.log(wrongAnswer);
        }

///即使我未按正确答案或什至没有选择任何内容,当我按下按钮时,“正确答案”部分也会不断上升。我不知道出了什么问题,即使对于正确的选项和错误的选项,我的选项的值也不同。

1 个答案:

答案 0 :(得分:0)

您是在第一次加载页面时选择checkbox的值,然后每次单击Done按钮时都会使用该值。因此页面加载:

// this returns the value for the first element with class correct1
// in this case that value happens to be the correct answer so on
// page load you've already "selected" the right answer that's why 
// consecutive clicks to done just increment the correct counter
var answer1 = $( ".correct1" ).val();
// answer1 = "C";

要解决此问题,您可以在用户每次单击checked按钮时获得Done单选按钮的值:

var correctAnswer = 0;
var wrongAnswer = 0;
var unAnswered = 0;

$("button").on("click", function() {
    // get the current checked radio button
    let answer1 = $('.correct1:checked').val();
    console.log(answer1);
    if(answer1 == "C"){

        correctAnswer++;
        $("#CA").html(correctAnswer);
        console.log(correctAnswer);

    }
    else if (answer1 == "F"){

        $("#IA").html(wrongAnswer);
        wrongAnswer++;
        console.log(wrongAnswer);
    }
});

这是现场演示:
https://www.bootply.com/90xDYoh3vL