所以我有一个提交照片的表格(总共 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')
});