javascript - 委托(delegate)uploadfile事件来控制动态加载

标签 javascript jquery file-upload jquery-events

我正在使用分配给 #fileupload 控件的 fileupload 事件。当我将此代码放入静态页面时,它运行良好,但我希望此控件加载到 JavaScript 模板中,如下所示:

<script type="text/template" id="propertyCollectionTemplate">
    <span id="firstUpload" class="btn btn-success fileinput-button">
    <i class="glyphicon glyphicon-plus"></i>
    <span>Select files...</span>
    <!-- The file input field used as target for the file upload widget -->
    <input id="fileupload" type="file" name="files[]" multiple>
    </span>    
</script>

在我的舞台中单击一个表格行时会加载此模板

$('table.collection tbody tr').click(function (e) {
        e.preventDefault();
        var m = page.properties.get(this.id);
        page.showDetailDialog(m);

});

在我的 showDetailDialog 函数中有以下代码:

showDetailDialog: function (m) {

        // show the modal dialog
        $('#propertyDetailDialog').modal({ show: true });
        // ... fecth all data for my other controls....

这是我在静态模式下绑定(bind)的上传事件:

 $('#fileupload').fileupload({
     url: page.url,
     dataType: 'json',
     done: function (e, data) {
         alert("hola");
         $.each(data.result.files, function (index, file) {
             $('#propertyimage').val("/propertylocator/upload/server/php/files/" + file.name);
         });
         $('#progress .progress-bar').css('width', 0 + '%');
     },
     progressall: function (e, data) {
         var progress = parseInt(data.loaded / data.total * 100, 10);
         $('#progress .progress-bar').css('width', progress + '%');
     }
 }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');

如果我在加载模态弹出窗口时复制并粘贴此事件到 Chrome 控制台中,则效果很好,但我不知道在加载模板后如何委托(delegate)此事件。

最佳答案

有两种方法:

第一种方法:

最初启动fileupload(插入模板之前)并设置更改属性:

$('#fileupload .files').on('change', ':file', function (e) {
    $('#fileupload').fileupload('add', {
        fileInput: $(this)
    });
});

更多详细信息请参见:https://github.com/blueimp/jQuery-File-Upload/issues/1260

第二种方式:

在回调中插入模板之后绑定(bind)fileupload,例如:

$('table.collection tbody tr').click(function (e) {

    // your 'click' code
    e.preventDefault();
    var m = page.properties.get(this.id);
    page.showDetailDialog(m);

    // bind fileupload
    $('#fileupload').fileupload({

        // ...

    });

});

更多详细信息请参见:jQuery File Upload not working when file input dynamically created

关于javascript - 委托(delegate)uploadfile事件来控制动态加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23393025/

相关文章:

javascript - 不能在其他函数中使用一个函数的结果

javascript - Scriptaculous Droppables onDrop 回调,如何引用每个元素?

javascript - 从 Javascript 中的 JWT 中提取 'Roles'

javascript - 使输入字段的一部分不可编辑

node.js - Sails.js 船长 : How to read the uploaded file stream during upload?

php - 使用 "load data infile"时如何忽略 CSV 文件的最后五行

javascript - 单击事件后无法从 url 中删除主题标签

javascript - 删除前检查复选框

jquery - 快速 jQuery 选择器子元素

使用 AngularJS 上传 HTML5 文件