【问题标题】:Attaching jQuery plugin to dynamically generated elements将 jQuery 插件附加到动态生成的元素
【发布时间】:2013-08-28 09:14:22
【问题描述】:

我正在使用插件来管理我的上传者。但问题是每次你点击按钮时我都会添加新的文件上传器,所以插件只加载页面加载时已经创建的元素。这是我所拥有的一个例子:

<div id="uploaders">
    <div class="container">
        <div class="file-uploader">
            <input type="files" name="files[]">
        </div>
    </div>
    <button>Add new uploader</button>
</div>
<script src="js/file-uploader.min.js"></script>
<script>
$(function() {
    $uploaders = $('#uploaders');
    $uploaders.find('.file-uploader input').myPlugin({ options }).on('uploadfinished', function(){ console.log('File uploaded!'); });
    $uploaders.find('button').on('click', function(){
        $(this).closest('.container').append('<div class="file-uploader"><input type="files" name="files[]"></div>'); //This uploader won't load myPlugin
    });
});
</script>

有没有办法可以将该插件附加到所有生成的文件上传器?我知道我可以在附加 HTML 之前立即完成,但这会是个问题,因为我必须再次定义所有配置和事件...

【问题讨论】:

    标签: jquery jquery-plugins append


    【解决方案1】:

    使用 jQuery .on() 方法并使用此处描述的“委托事件”方法:http://api.jquery.com/on/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      相关资源
      最近更新 更多