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

时间:2011-07-13 20:24:36

标签: javascript html

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

代码:         

        ...

        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>
        ...

我想我的问题是......有没有更好的方法呢?

感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

您应该使用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);
        }
    }