将事件附加到动态呈现字段的更简洁的方式

cleaner way to attach event to dynamically rendered field

本文关键字:字段 简洁 方式 事件 动态      更新时间:2023-09-26

我为动态呈现的表单字段附加了一个更改事件:

        var html ='';
        html += '<div class="Gallery-overlayContentWrapper">';
        html += '<center>';
        html += '<h3>'+self.data('uploadHeading')+'</h3>'
        html += parent;
        html += '<form id="Gallery-uploadForm" enctype="multipart/form-data" method="post">';
          html += '<input type="hidden" name="Gallery-Parent" id="Gallery-Parent" value="'+self.data('activeFolder')+'" />';
          html += '<p><input type="file" name="file1" id="file1"></p>';
          html += '<p><progress id="Gallery-uploadProgress" value="0" max="100"></progress></p>';
        html += '</form>';
        html += '</center>';
        html += '</div>';
        $(self).find(".Gallery-"+self.data('overlayType')).append(html);
        $(self).find(".Gallery-"+self.data('overlayType')).fadeIn(); //This only covers the thumbs area
        setTimeout(function(){
            $(self).find('#file1').change(function(){
                self.data('uploadFile')(self);
            });
        },1000);

这是可行的,但是像这样依赖于1秒后渲染的元素感觉有点粗糙,是否有更干净的方法来做到这一点?

不需要使用timeout,在附加

之后附加它
    $(self).find(".Gallery-"+self.data('overlayType')).append(html);
    $(self).find('#file1').change(function(){
            self.data('uploadFile')(self);
        });
    $(self).find(".Gallery-"+self.data('overlayType')).fadeIn(); 

使用委托

$(document).on('change', '#file1', function(){
                self.data('uploadFile')(self);
            });