因此,我有一个表单来提交照片(总共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')
});发布于 2012-08-09 00:49:31
在我看来,您正在尝试根据用户选择的内容来附加/删除事件处理程序。这是低效的,而且容易出错。
在您的示例中,每次添加照片时都会调用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类(以便它与过滤器不匹配)。
https://stackoverflow.com/questions/11868960
复制相似问题