首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jquery事件被多次调用

Jquery事件被多次调用
EN

Stack Overflow用户
提问于 2012-08-09 00:27:38
回答 2查看 786关注 0票数 0

因此,我有一个表单来提交照片(总共8张),我正在尝试应用一个小效果:一旦你选择了一张照片,按钮就会隐藏,文件名与一个'X‘一起显示,以删除它的选择。

但是,当我添加多张照片并试图删除其中一张照片时,该事件会被多次调用,并且我单击的次数越多,就会触发更多的事件,所有这些事件都来自同一个元素。

有没有人能弄明白?

代码语言:javascript
复制
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')
});
EN

Stack Overflow用户

回答已采纳

发布于 2012-08-09 00:49:31

在我看来,您正在尝试根据用户选择的内容来附加/删除事件处理程序。这是低效的,而且容易出错。

在您的示例中,每次添加照片时都会调用Upload.bindEvents(),而不会清除之前的所有处理程序。您可能会调试,直到您不再泄漏事件侦听器,但这是不值得的。

jQuery.on非常强大,允许您将处理程序附加到DOM中尚未包含的元素。您应该能够这样做:

代码语言:javascript
复制
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类(以便它与过滤器不匹配)。

票数 2
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11868960

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档