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

时间:2016-01-02 06:51:19

标签: javascript jquery function counter reset

问题

我在页面底部有一个resetQuiz()测验按钮,该按钮应该将分数设置为0,但如果此人得到了25个正确答案,请点击.button__reset,然后执行再次测验,它变为26而不是0。

直播链接: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();
});

3 个答案:

答案 0 :(得分:1)

您在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);
}

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

答案 1 :(得分:1)

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

而不是var score = 0; resetQuiz 中使用score = 0;

答案 2 :(得分:1)

更改var score = 0; to score = 0;

除了最初的情况外,对所有情况都这样做。在javascript中,可以有两个具有相同名称的变量。所以当你说:

var score = 0;

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

相关问题