更新元素后,jQuery hasClass()函数无法正常工作

sia*_*one 3 javascript jquery

我已经创建了一个按钮,允许我平台的用户提交一个帖子,或者如果再次按下该按钮则删除之前的投票.

问题是当用户第二次点击按钮时,在投票后没有任何反应.

这是管理按钮行为的代码:

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"));
    });
}
Run Code Online (Sandbox Code Playgroud)

removeVotevotePlus功能还需要修改按钮的方面的护理:

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");
            }
        }
    )
}
Run Code Online (Sandbox Code Playgroud)

基本上$(".timeline-action-plus").hasClass("btn-success")似乎只有在按钮类由removeVotevotePlus函数更新之前才能工作.

编辑:

这是按钮:

<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>
Run Code Online (Sandbox Code Playgroud)

Jam*_*lly 7

您需要hasClass在点击功能中移动支票:

$(".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"));
});
Run Code Online (Sandbox Code Playgroud)

现在,每次单击元素时都会执行检查.