2013-03-25 200 views
3

我有一個表格,其中一些數據顯示給用戶。有CRUD'ing數據的按鈕,我在前端使用jQuery。當按下按鈕時,將顯示一個模式,並通過ajax請求更新數據。jQuery事件被觸發不止一次

我的問題是:如果我點擊更新按鈕,關閉模式,點擊另一個更新按鈕並更新數據,它會在上每點擊一行保存相同的新數據。簡而言之,我的代碼正在執行多次,與我執行的點擊次數一樣多。

這裏是我的代碼:http://pastebin.com/QWQHM6aW

$(document).ready(function() { 
    /*--------------------------------------------*/ 
    // GENERAL 
    /*--------------------------------------------*/ 
    function loadingStart() { 
     $("#overlay").show(); 
     $("#loading").show(); 
    } 

    function loadingDone() { 
     $("#overlay").hide(); 
     $("#loading").hide(); 
    } 

    $(document).ajaxStop(function() { 
     loadingDone(); 
     //alert('Ajax Terminou'); 
    }); 

    function reloadRows() { 
     $.post("ajax.php", { type: "AllRows" }) // Faz um post do tipo AllRows. 
     .done(function(data) { 
      alert(data); 
      //$("#tbody").html(data); 
     }); 
    } 
    $("body").on("click", ".update-socio-btn", updateSocio); 
    /*--------------------------------------------*/ 
    // UPDATE 
    /*--------------------------------------------*/ 
    function updateSocio(event) { 
     $("#socio-form input").val(''); // Apagar os valores do form. 
     loadingStart(); // Começar o Loading... 
     var id = $(this).closest('tr').find('.id-holder').html(); // Pegar o valor do id holder e salvar na var id. 
     $("#socio-form input").removeClass("input-transparent").prop("disabled", false); // Queremos ver e utilizar os inputs. 
     $(".modal-footer").removeClass("hidden"); // Queremos ver o footer do modal. 
     $(".btn-modal").attr("id", "update-btn-confirm"); // Atribui o id: update-btn-confirm ao .btn-modal. 

     $.post("ajax.php", { type: "read", id: id }) // Faz um post do tipo Read e retorna os valores nos inputs correspondentes 
     .done(function(data) { 
      console.log('read'); 
      jsonOBJ = jQuery.parseJSON(data); 
      for (var key in jsonOBJ) { 
       $("input[name=" + key + "]").val(jsonOBJ[key]); 
      } 
     }); 

     $("#update-btn-confirm").click(function() { // Quando clicar no botão de salvar. 
      var formArray = $("#socio-form").serializeArray(); // Pega todas as informações dos inputs e transforma em um array json. 
      $.post("ajax.php", { type: "update", id: id, inputs: formArray }) // Faz um post do tipo Update. 
      .done(function(data) { 
       console.log('uptade'); 
       alert(data); 
       event.stopPropagation(); 
      }); 
     }); 
     event.preventDefault(); 
    } 
}); 

我強烈懷疑問題在於對.on方法,但我有一個很難精確定位它。我知道我可以使用.live().bind(),但我試圖避免它,因爲兩者都被棄用。

有什麼建議嗎?

回答

4

每次單擊帶有類.update-socio-btn的元素時,都會運行updateSocio函數。每次運行updateSocio時,都會在#update-btn-confirm上綁定新的點擊事件。

您可以通過移動updateSocio函數之外的點擊綁定並僅綁定一次事件處理程序來解決此問題。

+0

作品很有魅力,謝謝! – tassiodias 2013-03-25 01:43:25