简体   繁体   中英

Calling a function inside click handler, not running

Problem

I'm calling the function resetSelection that should remove .is-active classes and add a class of is-inactive to a list of hockey players, amongst other things, after the submit button .btn--submit has been clicked.

Right now, the .is-active classes remain on the picked players and the function does not run?

index.html

<button class="btn btn--submit"><img src="src/img/ballot-alt.png" class="image--ballot">Submit Vote</button>

scripts.js

function resetSelection() {
    $(".btn--reset").on("click", function(){
        $(".picked").removeClass("is-active");
        $(".picked").addClass("is-inactive");
        $(".icon-checkmark").removeClass("is-completed");
        $(".btn--submit").hide();
        $(".btn--submit").removeClass("slideLeft");
        starredGoaltenders = 0;
        starredDefencemen = 0;
        starredForwards = 0;
        console.log(starredGoaltenders, starredDefencemen, starredForwards);
    });
} resetSelection();

$(".btn--submit").on("click", function(){
    console.log("Clicked");
    resetSelection();
});

Your function binds a click handler event to elements with the class btn--reset . Consider refactoring resetSelection to include the logic within that event handler, but not the event handler itself:

function resetSelection() {
    $(".picked").removeClass("is-active");
    $(".picked").addClass("is-inactive");
    $(".icon-checkmark").removeClass("is-completed");
    $(".btn--submit").hide();
    $(".btn--submit").removeClass("slideLeft");
    starredGoaltenders = 0;
    starredDefencemen = 0;
    starredForwards = 0;
    console.log(starredGoaltenders, starredDefencemen, starredForwards);
}

$(".btn--reset").on("click", resetSelection);

$(".btn--submit").on("click", function(){
    console.log("Clicked");
    resetSelection();
});

Your reselectSelection() function contains an click event handler for .btn--reset . Remove that handler and it should work for you because you want to trigger reset function when .btn--submit is clicked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM