事件调用在 ajax 替换元素后多次

Event call multiple time after ajax replace element

本文关键字:元素 替换 调用 ajax 事件      更新时间:2023-09-26

我对Jquery事件有问题。在我用另一个元素替换该元素但类型和相同的 id 后,Jquery Event 被多次调用。

// 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 成功后调用转售事件。那么,为什么在调用 AJAX 的同时多次调用事件click button.addImage呢?这是 html:

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

您很可能再次加载此脚本或调用再次添加此事件处理程序的函数

最好的解决方法是查找再次调用此事件处理程序的位置。

解决方法是将事件命名为命名空间,并始终使用 off() 删除事件处理程序,然后再再次添加

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

使用 one()

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

谢谢。我找到了答案。即在"开"之前使用"关闭",如下所示:我更新了查利特弗先生的回答。

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