测验完成后将分数重置为 0

Resetting score to 0 after quiz completed

问题

我在页面底部有一个 resetQuiz() 测验按钮,它应该将分数设置回 0,但如果这个人已经得到 25 个正确答案,请单击 .button__reset 并然后再做一次测验,它变成了 26 而不是 0.

直播link:https://s3.amazonaws.com/bsunproduction/yearinreview/index.html

scripts.js

/*-------------------------------------
QUIZ
--------------------------------------*/

// Keep track of score
function showScoreBox() {
    var scrollDepth = $(window).scrollTop();
    var divPosition = $(".quiz__header").offset().top - 45;
    var windowWidth = $(window).width();
    // console.log(windowWidth);

    if (scrollDepth > divPosition && (windowWidth > 768)) {
        $(".quiz__score").show();
        $(".quiz__score--mobile").hide();
    } else {
        $(".quiz__score").hide();
        $(".quiz__score--mobile").show();
    }
} showScoreBox();

$(window).on("scroll", function(){
    showScoreBox();
});

$(window).on("resize", function(){
    showScoreBox();
});

var score = 0;

$(document).on("click", ".quiz__response", function(){
    $(this).siblings().addBack().addClass("is--unclickable");
    $(this).siblings().show("quiz__info");  // Show extra info
    console.log("Clicked");

    if ($(this).hasClass("answer--true")) {
        $(this).addClass("is--true");
        $(this).find("i").show();
        $(this).siblings().find("i").show();

        // Update score
        score++
        console.log(score);
        $(".quiz__correct").html(score);
        $(".quiz__correct--mobile").html(score);
        rainConfetti();
    } else {
        // $(this).addClass("is--true");
        // $(this).siblings().addClass("is--false");
        // $("quiz__info").removeClass("is--false");
        $(this).addClass("is--false");
        $(this).find("i").show();
        $(this).siblings().find("i").show();
    }
});

/*-------------------------------------
RESET
--------------------------------------*/

function resetQuiz() {
    var score = 0;
    $(".quiz__response").removeClass("is--true is--false");
    $(".quiz__response").removeClass("is--unclickable");
    $(".fa-check").hide();
    $(".fa-times").hide();
    $(".quiz__correct").html(score);
    $(".quiz__correct--mobile").html(score);
}

$(".button__reset").on("click", function(){
    var score = 0;
    $("canvas").hide();
    resetQuiz();
});

您正在 resetQuiz 中再次宣布分数

function resetQuiz() {
    //var score = 0;
    // should be
    score = 0;
    $(".quiz__response").removeClass("is--true is--false");
    $(".quiz__response").removeClass("is--unclickable");
    $(".fa-check").hide();
    $(".fa-times").hide();
    $(".quiz__correct").html(score);
    $(".quiz__correct--mobile").html(score);
}

由于局部变量 score 设置为零,因此不会反映在外部 score 变量中。

您正在创建一个新变量并为其分配值 0 而不是全局变量。

而不是 var score = 0;resetQuiz

中使用 score = 0;

改变var score = 0; to score = 0;

对除第一个案例之外的所有案例都执行此操作。在 javascript 中,可以有两个同名的变量。所以当你说:

var 分数 = 0;

您正在创建一个新变量,然后将其设置为 0。原始变量仍然具有旧值。