2015-10-16 83 views
0
$('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子句是工作的成功,意味着方法UpdatePostThumbsUp在控制器(MVC)是正常工作),但与else子句。 按钮HTML类似:jQuery的AJAX像社交网络

<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> 
+2

究竟是什么问题? –

+0

为什么else子句不起作用:( – Jen

+1

尝试将if($(this).toggleClass('btn btn-default'))'改为if($(this).hasClass('btn-default' )' – FBHY

回答

0

$(this).toggleClass('btn btn-default'),将始终返回jQuery的,即转化为boolean,所以你会经常去,如果分支。

尝试使用,如果($(this).hasClass('btn btn-default')),应该做的伎俩。

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