简体   繁体   中英

On click event not working in JQuery when button has class

Here's my current HTML and JavaScript code:

<button class="like_button" th:classappend="${#lists.contains(liked_profiles, profile)} ? unlike : like" th:value="${profile.email}">
   <i class="fa fa-thumbs-o-up" style="font-size:24px"></i>
</button>
$(document).ready(function (){
        $("button.like_button").on('click', function (){
            let email;
            console.log("Got In");
            if($(this).hasClass("like")){
                console.log("Got In if Statement for like");
                email = $(this).val();
                fetch("/api/like/" + email)
                    .then(res => console.log("Response, " + res))
                    .catch(err => console.log("Error, " + err))
                $(this).removeClass("like");
                $(this).addClass("unlike")
            }
            if($(this).hasClass("unlike")){
                console.log("Got In if Statement for unlike");
                email = $(this).val();
                fetch("/api/unlike/" + email)
                    .then(res => console.log("Response, " + res))
                    .catch(err => console.log("Error, " + err))
                $(this).removeClass("unlike");
                $(this).addClass("like");
            }
        });
    });

When ever I click on the like button the on click event never runs. Been looking online to see if anyone has had the same issue with no luck. Any help would be much appreciated.

Try change to:

$(".like_button").on('click', function (){

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