Javascript:元素.innerHTML += "…"重置文件输入'
Javascript: element.innerHTML += "..." resetting file input's
我开始了一个新项目,我开始做的第一件事真的很痛苦。我正在制作一个表单,人们可以在其中上传许多"附件"。问题是,当用户按下"添加附件"键时,所有的附件都会被重置。
代码:
...
function addAttachment() {
var list = document.getElementById("attachments");
var index = 1;
for(; index < 6;index++) {
if(document.getElementById("attachment" + index) == null) {
break;
} else if(document.getElementById("attachment" + index).value == "") {
index = -1;
break;
}
}
if(index == 5) {
alert ('You can only have a maximum of 5 attachments!');
} else if(index == -1) {
alert ('One of your attachments do not have a file in it! Put your file in there first!');
} else {
list.innerHTML += '<br /><input size="1" type="file" id="attachment' + index + '" name="attachment' + index + '"/>';
}
}
...
<li id="attachments">
<label>Attachments:</label> (<a onclick="addAttachment()" href="#">Add an Attachment</a>)
<br /><input size="1" type="file" id="attachment1" name="attachment1"/>
</li>
...
我想我的问题是……有更好的方法吗?谢谢你的帮助!
你应该使用DOM和appendChild而不是设置innerHTML
function addAttachment() {
var list = document.getElementById("attachments");
var index = 1;
for(; index < 6;index++) {
if(document.getElementById("attachment" + index) == null) {
break;
} else if(document.getElementById("attachment" + index).value == "") {
index = -1;
break;
}
}
if(index == 5) {
alert ('You can only have a maximum of 5 attachments!');
} else if(index == -1) {
alert ('One of your attachments do not have a file in it! Put your file in there first!');
} else {
var br = document.createElement("br");
var newAttachment = document.createElement("input");
newAttachment.size = 1;
newAttachment.type = "file";
newAttachment.id = "attachment"+index;
newAttachment.name = newAttachment.id;
list.appendChild(br);
list.appendChild(newAttachment);
}
}
相关文章:
- 为什么spyOn"停止函数“”的所有执行;Jasmine(要求澄清Jasmine 2.2间谍文件)
- Node.js服务器问题-已添加“/"在浏览器中查找文件时
- Django,HTML,JS:<img src=“#">可以在HTML中工作,但不能在JS文件中工作
- 在Asp.net的空网站中,如何改变"Web.config”;使内容(.js)文件显示在浏览器中,而不是下载
- "npm运行构建“;模块解析错误”;您可能需要一个适当的加载程序来处理此文件类型&”;
- Chrome、Firefox转换“:"至“-"以及“_"分别显示在文件保存对话框中
- 说明Node.js项目:是否只有一个"服务器文件“;在node.js中
- 如何在ajax中返回文本文件值Asynchronous"Synchronous正在被弃用”;
- 如何在Wordpress文件中添加自定义javascript代码"single.php”;
- 当我运行返回()时"":""Javascript中的语法,只有当我将文件保存为PHP
- MVC 4无法定位“;脚本"文件夹
- "ReferenceError未知插件“;当我尝试使用babel-cli转换目录中的js文件时
- 如何检查“;文件打开"窗口是用javascript打开的
- "不安全的JavaScript尝试访问URL为..的帧"使用本地文件
- "文件“;在mozilla扩展js模块中
- "格式不正确的JSON流”;当从SharePoint 2013 REST API对文件使用moveto或cop
- "模块化”;Javascript文件
- "在文件对话框中取消“;事件
- 正在尝试在IE7中测试HTML文件"$"是javascript部分的未定义错误
- "$(文件);在事件stopPropagation之后不触发$(a) 在“;而不触发新的元素