2017-02-27 78 views
0

我使用JQuery與Ajax。 我做點擊後,解除綁定後,ajax綁定點擊。 但綁定方法不起作用。 請幫我Ajax後不工作綁定事件

$(".lang").on("click", function (e) { 

    $(this).unbind('click'); 

    if ($(this).hasClass("disabledLanguage")) { 

     return false; 
    } 
    var token = $('[name=__RequestVerificationToken]').val(); 

    $.ajax({ 
     type: "POST", 
     url: Host + "Language", 
     data: { __RequestVerificationToken: token, Code: $(this).data("code") }, 
     success: function (data) { 

      if (data.IsCompleted) { 

       //window.location = window.location.href; 
      } 
      else { 
       //alert("Error"); 
      } 

      $(this).unbind('click'); //<----Notworking 
     } 
    }); 
     return false; 

    }); 
+1

'this',在阿賈克斯成功的回調,是不是更詳細說一下你認爲它是 - '變種_this = this'在ajax調用之前,然後在成功回調函數中使用'$(_ this).unbind' ...然後瞭解'this'如何工作 –

回答

1
/** 
* make a function to handle the click event stand alone 
* it's good for reuse and test 
*/ 
function clickHandler(e){ 
    /** 
    * cache the result of $(this) 
    * for performance and reuse in another function context 
    */ 
    var $lang = $(this); 

    $lang.unbind('click', clickHandler); 

    if ($lang.hasClass("disabledLanguage")) { 
     return false; 
    } 

    var token = $('[name=__RequestVerificationToken]').val(); 

    $.ajax({ 
     type: "POST", 
     url: Host + "Language", 
     data: { __RequestVerificationToken: token, Code: $lang.data("code") }, 
     success: function(data) { 

      if (data.IsCompleted) { 

       //window.location = window.location.href; 
      } else { 
       //alert("Error"); 
      } 

      /** 
      * doing after click,unbind and after ajax bind click 
      * so it should be bind click but not unbind click 
      */ 
      $lang.bind('click', clickHandler); 
     } 
    }); 
    return false; 
} 

$(".lang").on("click", clickHandler); 

可能這可以幫助你,並在評論

+0

這非常非常非常感謝shuizhongyuemin :) –