2016-02-29 42 views
-1

我遇到jquery事件的問題。在我用另一個元素替換那個元素之後,多次調用Jquery事件,但是相同類型和相同的ID。ajax替換元素後多次發生事件調用

// 1. ajax call success and replace my block 
// 2. This is my event that I want it happen. 

$(document).on("click", ".polaroid button.addImage", function(event) { 
    event.preventDefault(); 
    // trigger browse file to upload 
    $(event.target).closest("div.polaroid").find("input[type=file]").trigger("click"); 
}); 

此代碼被用於轉售AJAX成功後調用事件。那麼,爲什麼button.addImage與事件click多次調用AJAX被稱爲? 這是HTML:

<div class="col-md-3 polaroid"> 
 
\t <img src="images/ingredient/default_img.png" title="Main image" /> 
 
\t <input type="file" name="file-image" style="display:none"/> 
 
\t <button type="button" data-toggle="tooltip" title="Add" class="btn addImage"><i class="glyphicon glyphicon-plus icon-plus"></i></button> 
 
</div>

+0

你把這行多次?你只應該這樣調用一次。如果你不能僅僅調用它一次,那麼你需要解除它。 – epascarello

+0

只有一次。我檢查了。 – thanhlong

+0

可能再次加載這個腳本 – charlietfl

回答

0

你最有可能被再次載入此腳本或調用一個函數,又增加了此事件處理程序

最好的解決辦法是找到這個事件處理程序的位置再次被調用。

一種解決方法是命名空間中的事件,總是重新加入

$(document) 
    .off('click.polaroid') 
    .on("click.polaroid", ".polaroid button.addImage", function(event) { 
     // other code 
    }); 
0

使用一個()

$(document).one("click", ".polaroid button.addImage", function(event) {

+0

不幸的是,如果你再次調用它...它會添加另一個'one()'並且每個將被調用一次 – charlietfl

+0

簡單的演示來解釋https://jsfiddle.net/crn1dp9c/ – charlietfl

0

由於之前刪除使用off()事件處理程序。我找到答案。在「開」之前使用「off」,如下所示: 我更新Mr.charlietfl的答案。

$(document) 
 
    .off('click',".polaroid button.addImage") 
 
    .on("click", ".polaroid button.addImage", function(event) { 
 
     event.PreventDefault(); 
 
     // other code 
 
    });