2016-11-09 13 views
0

我寫了一個更新按鈕點擊代碼,將顯示引導模式與2個按鈕取消,刪除。我注意到,點擊update按鈕後,模式顯示與button.however,如果我按delete按鈕上該模式然後奇怪的delete按鈕在1上調用它自己兩次或更多。結果ajax也發射了兩次。我可能會有任何事件類。這裏是示例代碼。爲什麼模式按鈕多次調用?

<button type="button" id="update" class="btn btn-success" style="display:none;">Update</button> 
<div class="modal-footer"> 
    <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel">Cancel</button> 
    <button type="button" class="btn btn-danger btn-ok" id="btn-delete">Delete</button> 
</div> 

$("#update").click(function (e) { 
    e.preventDefault(); 
    $('#confirm-delete').modal("show"); 
}); 

$('#confirm-delete').on('show.bs.modal', function(e) { 
    var instance = $(this); 
    $("#btn-delete").click(function(event) { 

     var data_x = 101; 
     event.preventDefault(); 
     instance.modal('hide'); 
     $.ajax({ 
      url: 'delete_data.php', 
      type: "post", 
      async: true, 
      data: ({ 
       data_x: data_x 
      }), 
      success: function(data) { 
       alert(data); 
      } 
     }); 


    }); 

}); 

請幫助我理解它&決心it.thanks

+0

你確定你是不是附加的事件處理程序兩次?即show modal => attach handler => hide modal => show modal => attach處理程序(哦,哦,2個處理程序)。在這種情況下,您需要重新組織一次才執行附加處理程序代碼。 –

+0

這是否會一直髮生它所謂的兩次或有時會稱之爲更多? –

+0

您確定$(「#update」)。click(function(e){不會被調用兩次嗎? –

回答

1

你正在創建每次打開模態時附加的點擊功能。做一次:

$('#confirm-delete').one('show.bs.modal', function(e) { 
// --------------------^ 
    $("#btn-delete").click(function(event) { 

另外,使用事件代表團做模態的回調(內document.ready任何地方)以外:

$(document).on('click', '#confirm-delete', function() { 
    // ... 
+0

Hello @isherwood。爲你的答覆。我嘗試了你的建議。但仍然沒有working.please幫助 – user5005768

+0

你試過哪個?或者應該工作。也許創建一個[Fiddle](http://jsfiddle.net)來演示問題。 – isherwood

相關問題