Jquery ajax喜欢社交网络

时间:2015-10-16 16:11:04

标签: javascript jquery ajax

$('button[id="btnLike"]').on('click', function (e) {
            var userId = $("#logedUserId").val();
            var postId = $(this).data('id');
            if ($(this).toggleClass('btn btn-default')) {
                $(this).toggleClass('btn btn-info');
                $.ajax({
                    url: '@Url.Action("UpdatePostThumbsUp", "Main")',
                    type: 'POST',
                    data: { 'userId': userId, 'postId': postId, 'flag': true },
                    cache: false
                });
            }
            else {
                $(this).toggleClass('btn btn-default');
                $.ajax({
                    url: '@Url.Action("UpdatePostThumbsUp", "Main")',
                    type: 'POST',
                    data: { 'userId': userId, 'postId': postId, 'flag': false },
                    cache: false
                });
            }
        });

我不知道为什么它只使用了if子句(if子句是工作成功,意味着控制器(MVC)中的方法UpdatePostThumbsUp正常工作),但不能使用else子句。 像html中的按钮:

<button type="button" id="btnLike" class="btn btn-default" style="font-size:11px;padding:3px 6px" data-id="@p.PostId">
                    <span class="glyphicon glyphicon-thumbs-up"></span> Like
                </button>

1 个答案:

答案 0 :(得分:0)

$(this).toggleClass('btn btn-default')将始终返回 jQuery ,转换为boolean true ,因此您将始终转到if分支

尝试使用if ($(this).hasClass('btn btn-default')),应该这样做。

来源:http://api.jquery.com/toggleclass/

相关问题