多次调用 Jquery 事件

Jquery event being called multiple times

本文关键字:事件 Jquery 调用      更新时间:2023-09-26

所以我有一个提交照片的表格(总共 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"的事件。否则,您将添加更多点击事件。这就是为什么您会看到越来越多的点击被触发。