【问题标题】:cleaner way to attach event to dynamically rendered field将事件附加到动态呈现的字段的更简洁的方法
【发布时间】:2015-10-15 09:52:03
【问题描述】:

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

        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 秒后渲染的元素感觉很糟糕,有没有更清洁的方法来做到这一点?

【问题讨论】:

  • 委托不会对资源要求更高,只要有任何事情触发我的页面发生更改,浏览器就会查找事件?

标签: javascript jquery html timeout


【解决方案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);
            });

【讨论】:

  • 委托不会对资源要求更高,只要有任何事情触发我的页面发生更改,浏览器就会查找事件?
  • 至于您的第一个建议(我的初始代码减去超时的事情),在浏览器完成渲染要附加的 html 之前执行该代码(设置更改事件)的风险。
  • @MattWelander,如果您使用 self 而不是 document 作为容器,则可以最大限度地减少性能损失。尽管如此,我认为两者之间的性能差异可以忽略不计,除非你有一个 huge document
  • @MattWelander,除非 input 对用户可见,否则无法触发 change 事件
猜你喜欢
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
相关资源
最近更新 更多