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

时间:2015-07-24 16:20:35

标签: javascript jquery html timeout

我将更改事件附加到动态呈现的表单字段,如下所示:

        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秒后渲染的元素感觉很乱,有没有更清晰的方法呢?

1 个答案:

答案 0 :(得分:1)

无需使用超时,在附加

后立即附加
    $(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);
            });