首页 > 解决方案 > 添加其他文件上传字段

问题描述

我正在使用此代码允许用户创建其他上传字段。正在创建字段,用户可以选择一个文件,但它永远不会添加到输入字段中。唯一有效的是第一个。在 firebug 中,我注意到创建的附加字段没有事件侦听器。

<script>
$(document).ready(function () {
    var next = 1;
    $(".add-more").click(function (e) {
        e.preventDefault();
        var addto = "#field" + next;
        next = next + 1;
        var newIn = '<div id="field' + next + '" class="custom-file mt-3 mb-2"><label class="custom-file-label">NewFile ' + next + '</label><input class="custom-file-input" name="field' + next + '" type="file"><input type = "text" class="form-control mt-1 mb-1" name="field' + next + '" placeholder="Text" /></div>';
        var newInput = $(newIn);
        $(addto).after(newInput);
        $("#field" + next).attr('data-source', $(addto).attr('data-source'));
        $("#count").val(next);
    });

});

这是已经存在的输入和用户单击按钮添加新文件时生成的新放置的 HTML:

<div id="fields">
<div id="field1" class="custom-file mt-1 mb-3">
<input class="custom-file-input" id="field-1" name="field-1" type="file">
<label class="custom-file-label">New File 1</label>
<input type="text" class="form-control mt-1 mb-1" placeholder="New File">
</div>

<div id="field2" class="custom-file mt-3 mb-2">
<label class="custom-file-label">New File 2</label>
<input class="custom-file-input" name="field2" type="file">
<input type="text" class="form-control mt-1 mb-1" name="field2" placeholder="Please provide a brief description of the uploaded file">
</div>

<button id="b1" class="btn btn-success add-more mt-4" type="button">Add more files</button>
</div>

只是一个注释;我正在使用引导程序 4。

有人知道这是什么原因吗?

编辑:我刚刚添加了这段代码,当我尝试使用动态创建的输入上传时,警报是“未定义”

$("#fields").delegate("input[type=file]", "change", function () {
        alert($(this).attr("id"));
    });

我使用 Bhushan 提供的代码创建了一个小提琴,它似乎工作得很好。我想我的申请中可能有冲突。

http://jsfiddle.net/kogcyc/x1hphsvb/

谢谢

标签: javascriptjqueryinputbootstrap-4upload

解决方案


您只为字段输入而不是添加的新文件输入附加更改事件处理程序。

请更换

$("#fields").delegate("input[type=file]", "change", function () {
        alert($(this).attr("id"));
    });

with -- 这里我们使用附加更改事件处理程序,.on并且选择器将查找所有具有 id 以字段开头的文件输入

$(document).on("change","input[id^=field][type=file]",  function () {
        alert($(this).attr("id"));
    });

推荐阅读