gpt4 book ai didi

Javascript:element.innerHTML += "..."重置文件输入

转载 作者:行者123 更新时间:2023-11-28 13:58:31 24 4
gpt4 key购买 nike

我已经开始了一个新项目,而我所做的第一件事确实很痛苦。我正在制作一个表格,一个人可以在其中上传许多“附件”。问题是当用户按下“添加附件”时,所有附件都会被重置。

代码:

        ...

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);
}
}

关于Javascript:element.innerHTML += "..."重置文件输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6685161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com