Javascript:元素.innerHTML += "…"重置文件输入'

Javascript: element.innerHTML += "..." resetting file input's

本文关键字:quot 文件 输入 元素 Javascript innerHTML      更新时间:2023-09-26

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

代码:

        ...
        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);
        }
    }
相关文章: