首页 > 解决方案 > 多个动态 javascript 上传按钮

问题描述

我需要帮助动态创建上传按钮。

我创建了一个函数来为按钮创建inputlabel元素,并使用 CSS 格式化标签,以便在input隐藏主要元素时单击标签打开上传文件对话框窗口。

当我玩这个功能时,它成功生成了一个上传按钮,第一个按钮工作正常,但是因为标签的htmlfor标签正在寻找一个唯一的id,我似乎无法动态创建更多的上传按钮。

我试过用htmlForid替换,label.htmlFor = label.previousElementSibling;但这不起作用。

这是我所拥有的:

function addButton() {
var upload = document.createElement("input");

var col11 = document.createElement("td")

var upload = document.createElement("input");
    upload.type = "file";
    upload.id = "receipt";
    upload.className = "uploadClass";

    var label = document.createElement("label")
    label.innerHTML = `<i class='material-icons center'>file_upload</i>`;
    label.htmlFor = label.previousElementSibling;
    label.className = "custom-file-upload";

    col11.appendChild(upload)
    col11.appendChild(label)

这是CSS代码:

input[type="file"]{
display: none;
}

.custom-file-upload{
border: 1px solid #ccc;
display: inline-block;
padding: 6px 6px;
cursor: pointer; 
}

似乎问题是htmlFor为每个按钮标签创建动态标签?

标签: javascriptcss

解决方案


试试这个,我正在使用Date's 的getTime方法来生成一个id文件输入。在生成唯一 ID 时,请随意使用您喜欢的任何解决方案。

function generateInputId() {
   return new Date().getTime();
}

function addButton(inputId) {
    const input = document.createElement("input");
    const td = document.createElement("td")
    const label = document.createElement("label")

    input.type = "file";
    input.id = inputId;
    input.className = "uploadClass";
    
    label.innerHTML = `<i class='material-icons center'>file_upload</i>`;
    label.htmlFor = inputId;
    label.className = "custom-file-upload";

    td.appendChild(input)
    td.appendChild(label)
    return td;    
}

const row = document.getElementById("row")
const fragment = document.createDocumentFragment();

Array(3).fill(0).forEach(() => fragment.appendChild(addButton(generateInputId())));

row.appendChild(fragment);
input[type="file"]{
display: none;
}

.custom-file-upload{
border: 1px solid #ccc;
display: inline-block;
padding: 6px 6px;
cursor: pointer; 
}
<table>
 <thead>
    <tr>
      <td>One</td>
      <td>Two</td>
      <td>Three</td>
    </tr>
 </thead>
 <tbody>
   <tr id="row"></tr>
 </tbody>

</table>


推荐阅读