简体   繁体   中英

jQuery hasClass() function not working after element is updated

I have created a button that allows the users of my platform to upvote a post or remove the previously cast vote it if the button is pressed again.

The problem is that when the user clicks the button the second time, after the post has been voted nothing happens.

This is the code that manages the button's behavior:

if($(".timeline-action-plus").hasClass("btn-success")) {
    $(".timeline-action-plus").click(function(){
        rating.removeVote($(this).data("entry-id"), $(this).data("token"));
    });
} else {
    $(".timeline-action-plus").click(function(){
        rating.votePlus($(this).data("entry-id"), $(this).data("token"));
    });
}

The removeVote and votePlus functions also take care of modifying the button's aspect:

function votePlus(id, token) {

    $.post(
        "http://localhost/user/vote",
        {
            rating  : '1',
            entryID : id,
            _token  : token
        },
        function(result) {
            if(result === "OK"){
                $(".timeline-action-plus[data-entry-id=" + id + "]").removeClass("btn-default");
                $(".timeline-action-plus[data-entry-id=" + id + "]").addClass("btn-success");
            }
        }
    );
}

function removeVote(id, token) {
    $.post(
        "http://localhost/user/removeVote",
        {
            entryID : id,
            _token  : token
        },
        function(result) {
            if(result === "OK") {
                $(".timeline-action-plus[data-entry-id=" + id + "]").removeClass("btn-success");
                $(".timeline-action-plus[data-entry-id=" + id + "]").addClass("btn-default");
            }
        }
    )
}

Basically the $(".timeline-action-plus").hasClass("btn-success") seems to work only before that the button classes are updated by the removeVote and votePlus functions.

Edit:

This is the button:

<button class="btn btn-xs @if(Rating::userHasVoted(Auth::user()->username, $article->id)) btn-success @else btn-default @endif timeline-action timeline-action-plus" data-entry-id="{{$ID}}" data-toggle="tooltip" data-token="{{csrf_token()}}" id="vote{{$ID}}" Title="+1">
    <span class="glyphicon glyphicon-thumbs-up"></span>
    <span id="voteNumber{{$ID}}"></span>
</button>

You need to move the hasClass check inside your click function:

$(".timeline-action-plus").click(function(){
    if ($(this).hasClass("btn-success")) {
        rating.removeVote($(this).data("entry-id"), $(this).data("token"));
    else
        rating.votePlus($(this).data("entry-id"), $(this).data("token"));
});

This will now perform the check every time the element 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