Насочване към група бутони в теста, а не към всички въпроси от теста при кликване

Актуализация #1


  • Актуализирах index.html и scripts.js

Оставащ проблем

Ако щракна върху грешен отговор...

  • Това не придава клас на току-що щракнатия бутон
  • Дава is-falseклас за правилен отговор и quiz__info

Ако щракна върху правилния отговор...

  • Не дава is-false клас на грешни отговори

scripts.js (НОВО)

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++
        $(".quiz__correct").html(score);
        $(".quiz__correct--mobile").html(score);
    } else {
        // $(this).addClass("is--false");
        $(this).siblings().addClass("is--false");
        $(this).find("i").show();
        $(this).siblings().find("i").show();
    }
});

index.html (Всеки въпрос има почти тази структура)

        <div class="quiz__question question-5 question__sports">
            <h3>Question #5</h3>
            <p class="quiz__description">A former PGA Tour winner from Brandon passed away at the age of 63. Can you name him?</p>
            <div class="quiz__responses">
                <button class="quiz__response response-5 answer--false">Billy Casper <i class="fa fa-times"></i></button>
                <button class="quiz__response response-5 answer--false">Rory Woods <i class="fa fa-times"></i></button>
                <button class="quiz__response response-5 answer--true">Dan Halldorson <i class="fa fa-check"></i></button>
                <button class="quiz__response response-5 answer--false">Billy Hurley <i class="fa fa-times"></i></button>

                <div class="quiz__info">
                    <p><span class="answer">A: </span>Halldorson competed for nearly 30 years on the PGA Tour, winning the 1980 Pensacola Open. He also captured the 1986 Deposit Guaranty Golf Classic, which was an unofficial tour stop. All told, he had 28 top 10 finishes in 431 PGA Tour events, pocketing nearly $1.2 million in career earnings.</p>
                </div>
            </div> <!-- .responses -->
        </div> <!-- .question -->

Оригинален въпрос


Цел

Имам тест с 25 въпроса, всеки въпрос има 4 възможни отговора .quiz__response. Когато се щракне върху бутон, искам да направя следното, но само за отговорите, свързани с този конкретен въпрос, в момента той прилага следното към всички въпроси.

Когато се щракне върху бутон...

  • addClass(".is--unclickable") на тези четири отговора
  • .show() .fa-check ако отговорът е верен, .fa-times ако отговорът е грешен
  • addClass(".is--true") за промяна на фона на зелен, ако отговорът е правилен и addClass(".is--false") за промяна на фона на червен за останалите три отговора

JSFiddle: https://jsfiddle.net/ub0c6acv/

скриптове.js

$(function(){

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

    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;

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

        if ($(this).hasClass("answer--true")) {
            $(this).addClass("is--true");
            $(".fa-check").show();

            // Update score
            score++
            $(".quiz__correct").html(score);
            $(".quiz__correct--mobile").html(score);
        } else {
            $(this).addClass("is--false");
            $(".fa-times").show();
        }
    });

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

    function resetQuiz() {
      $(".quiz__response").removeClass("answer--true answer--false");
      var score = 0
      $(".quiz__correct").html(score);
      $(".quiz__correct--mobile").html(score);
    }

    $(".button__reset").on("click", function(){
     resetQuiz();
    });

    /*-------------------------------------
    CONFETTI
    --------------------------------------*/

    function rainConfetti() {

        if (score === 25) {
            canvas.show()
        }
    }

    /*-------------------------------------
    SMOOTH SCROLL
    --------------------------------------*/

    $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
});

index.html (фрагмент от тест)

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

  <div class="quiz">
            <div class="quiz__score">
                <p><span class="quiz__correct">0</span> / 25</p>
            </div>

            <h2 class="quiz__header" id="top">Take the quiz</h2>
            <p class="credit">How well have you been paying attention to what's been happening in southwestern Manitoba in 2015? Take our 25-question quiz to test your local news knowledge.</p>

            <div class="quiz__questions">
            <!-- <canvas id="confetti"></canvas> -->
                <!-- Question -->
                <div class="quiz__question question-1 question__sports">
                    <div class="wrapper">
                        <!-- <img src="http://placehold.it/500x300" alt="" class="quiz__image"> -->
                    </div>
                    <h3>Question #1</h3>
                    <p class="quiz__description">What Brandon Wheat King, who was drafted by the New York Islanders, lost his desire to play hockey and walked away from the team prior to this season starting?</p>
                    <div class="quiz__responses">
                        <button class="quiz__response answer--false">Kale Clague <i class="fa fa-times"></i></button>
                        <button class="quiz__response answer--false">Macoy Erkamps <i class="fa fa-times"></i></button>
                        <button class="quiz__response answer--true">Ryan Pilon <i class="fa fa-check"></i></button>
                        <button class="quiz__response answer--false">Colin Cloutier <i class="fa fa-times"></i></button>


                        <!-- The six­-foot-­two, 212­pound rearguard had 11 goals and 41 assists in 68 regular­ season games, with a goal and 11 assists in 19 playoff contests last season, paired mainly with Russian Ivan Provorov. In 193 regular­season games with Brandon and the Lethbridge,Hurricanes, Pilon has 23 goals, 93 assists and 116 penalty minutes. -->

                    </div> <!-- .responses -->
                </div> <!-- .question -->

                <!-- Question -->
                <div class="quiz__question question-2 question__sports">
                    <div class="wrapper">
                        <!-- <img src="http://placehold.it/500x300" alt="" class="quiz__image"> -->
                    </div>
                    <h3>Question #2</h3>
                    <p class="quiz__description">Which former Brandon skip refused to talk to the local media after losing his fifth provincial men’s curling championship game in six years at Westman Place?</p>
                    <div class="quiz__responses">
                        <button class="quiz__response answer--false">Russ Howard <i class="fa fa-times"></i></button>
                        <button class="quiz__response answer--false">Kerry Burtnyk <i class="fa fa-times"></i></button>
                        <button class="quiz__response answer--true">Mike McEwen <i class="fa fa-check"></i></button>
                        <button class="quiz__response answer--false">Braden Calvert <i class="fa fa-times"></i></button>
                    </div> <!-- .responses -->
                </div> <!-- .question -->

                <!-- McEwen’s Winnipeg based team of B.J. Neufeld, Matt Wozniak and Denni Neufeld lost to Ried Carruthers 5­3 at the Safeway Championship hosted by Brandon. -->
        </div> <!-- quiz -->

person Andrew Nguyen    schedule 01.01.2016    source източник


Отговори (1)


Първо, можете да използвате делегиране на събития [раздел Директно и делегирано събития], за да свържете един манипулатор на събития вместо един за всеки бутон.

$(".quiz__response").on("click", function(){
$(document).on("click", ".quiz__response", function(){

За да добавите само .is--unclickable към отговорите, свързани с конкретен въпрос, променете $(".quiz__response").addClass("is--unclickable");
на
$(this).siblings().addBack().addClass("is--unclickable");
или
$(this).parent().children().addClass("is--unclickable");

За да покажете fa-times или fa-check, променете
$(".fa-check").show();
$(".fa-times").show();
на $(this).find("i").show(); (както в оператора if, така и в else)

И добавете $(this).siblings().addClass("is--false"); във вашия оператор if, за да оцветите в червено останалите отговори, ако правилният е маркиран.

РЕДАКТИРАНЕ

Пълни js промени

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

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

      // Update score
      score++
      $(".quiz__correct").html(score);
      $(".quiz__correct--mobile").html(score);
    } else {
      $(this).addClass("is--false");
      $(this).find("i").show();
    }
  });
person CronosS    schedule 02.01.2016
comment
Просто имам нужда от малка корекция за един проблем, който виждам. Когато щракна върху неправилен отговор, това не добавя is--false към quiz__response, което току-що щракнах, а добавя този клас към правилния отговор и div quiz__info. Актуализирах scripts.js и index.html по-горе, които включват вашите препоръки. - person Andrew Nguyen; 02.01.2016
comment
Все още имам някои проблеми, редактирах въпроса по-горе. - person Andrew Nguyen; 02.01.2016