2016-02-29 46 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 
 
    });