javascript - 多个动态 javascript 上传按钮
问题描述
我需要帮助动态创建上传按钮。
我创建了一个函数来为按钮创建input
和label
元素,并使用 CSS 格式化标签,以便在input
隐藏主要元素时单击标签打开上传文件对话框窗口。
当我玩这个功能时,它成功生成了一个上传按钮,第一个按钮工作正常,但是因为标签的htmlfor
标签正在寻找一个唯一的id
,我似乎无法动态创建更多的上传按钮。
我试过用htmlFor
id替换,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
为每个按钮标签创建动态标签?
解决方案
试试这个,我正在使用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>
推荐阅读
- javascript - 无法使用 JSON 将 jqxScheduler 状态存储到 MySQL
- python - 编译错误:gcc:错误:无法识别的命令行选项'-R'
- polymer - 聚合物网络应用程序中的 Facebook“向我们发送消息”按钮
- image - 使用查询将图像插入 postgres 数据库
- linux - 在VI编辑器中如何在打开的文件中定义变量以通过gf打开其他文件
- typo3 - Typo3 RealURL:显示页面 id
- video-encoding - HM 参考软件中的多线程
- javascript - 当我不知道需要比较多少东西时,使用 switch 语句最简单的方法是什么?
- excel - 用户表单/多页 - 除非选择选项按钮,否则禁用下一个按钮
- sql - 如何将动态 XML 值列拆分并解析为多行?