多次调用 Jquery 事件
Jquery event being called multiple times
所以我有一个提交照片的表格(总共 8 张),我正在尝试应用一个小效果:一旦你选择了一张照片,按钮就会隐藏,文件名会显示一个"X"以删除其选择。
但是,当我添加多张照片并尝试删除其中一张照片时,该事件会被多次调用,我单击的次数越多,触发的多个事件就越多,所有这些都来自同一元素。
谁能弄清楚?
var Upload = {
init: function ( config ) {
this.config = config;
this.bindEvents();
this.counter = 1;
},
/**
* Binds all events triggered by the user.
*/
bindEvents: function () {
this.config.photoContainer.children('li').children('input[name=images]').off();
this.config.photoContainer.children('li').children('input[name=images]').on("change", this.photoAdded);
this.config.photoContainer.children('li').children('p').children('a.removePhoto').on('click', this.removePhoto);
},
/**
* Called when a new photo is selected in the input.
*/
photoAdded: function ( evt ) {
var self = Upload,
file = this.files[0];
$(this).hide();
$(this).parent().append('<p class="photo" style="background-color: gray; color: white;">' + file.name + ' <a class="removePhoto" style="color: red;" href="#">X</a></p>');
if(self.counter < 8) { // Adds another button if needed.
Upload.config.photoContainer.append( '<li><input type="file" name="images"></li>');
self.counter++;
}
Upload.bindEvents();
},
/**
* Removes the <li> from the list.
*/
removePhoto: function ( evt ) {
var self = Upload;
evt.preventDefault();
$(this).off();
$(this).parent().parent().remove();
if(self.counter == 8) { // Adds a new input, if necessary.
Upload.config.photoContainer.append( '<li><input type="file" name="images"></li>');
}
self.counter--;
Upload.bindEvents();
}
}
Upload.init({
photoContainer: $('ul#photo-upload')
});
据我所知,您正在尝试根据用户选择的内容附加/删除事件处理程序。这是低效的,容易出错。
在您的情况下,每次添加照片时都会调用Upload.bindEvents()
,而不会清理所有以前的处理程序。您可能会进行调试,直到不再泄漏事件侦听器,但这不值得。
jQuery.on 非常强大,允许您将处理程序附加到尚未在 DOM 中的元素。你应该能够做这样的事情:
init: function ( config ) {
this.config = config;
this.counter = 1;
this.config.photoContainer.on('change', 'li > input[name=images]', this.photoAdded);
this.config.photoContainer.on('click', 'li > p > a.removePhoto', this.removePhoto);
},
您只需将一个处理程序附加到photoContainer
,它将捕获从子项冒泡的所有事件,无论它们是何时添加的。如果要禁用其中一个元素上的处理程序,只需删除 removePhoto
类(使其与筛选器不匹配)。
你正在做很多事情:Upload.bindEvents();
在再次绑定这些"li"之前,您需要取消绑定这些"li"的事件。否则,您将添加更多点击事件。这就是为什么您会看到越来越多的点击被触发。
相关文章:
- 选择onclick事件jquery
- 用于多个类事件Jquery的单个函数
- 激发滑块's幻灯片事件jquery ui
- 设置重复按钮以注册点击事件jquery
- 保留当前点击事件jquery
- 启动/停止按键事件jquery
- 在事件jquery中插入一个函数
- 删除克隆的事件JQuery
- typeahead选择事件(jQuery)的动态绑定
- 触发自定义事件 Jquery
- 绑定两次或更多次的事件 jquery
- 单击时的事件 jquery 不起作用
- 在鼠标悬停事件 jquery 上显示边框的内容
- 同时触发两个鼠标事件 jQuery
- 焦点事件 jquery 组合框/自动完成
- 如何在页面中捕获“正文”和“正文”事件[Jquery].
- 将对象传递给事件 jQuery
- 验证“取消”上的字段 单击Onbeforeunload事件JQUERY
- 复选框单击事件 jQuery 不起作用
- 口述事件jquery顺序