简体   繁体   中英

<li> element can not be created dynamically using javascript

I am trying to upload Multiple file and even I am getting multiple file also.

but I am trying to display those selected file line by line so for that I am using tag but I am unable to create that here is my code

    <script type="text/javascript">
                        window.onload = function() {
                            var fileInput = document.getElementById('fileInput');

                            fileInput.addEventListener('change', function(e) {
                                var file1 = fileInput.files;
                                var output = [];
                                for(var i=0,f;f=file1[i];i++){
                                    output.push('<li>'+f.name+'</li>');
                                    alert(f.name);
                                    document.getElementById('list').innerHTML = '<ul>'+output+'</ul>';
                                }
                            });
                        }
                        </script>


                                <input type="file" id="fileInput" multiple="multiple" >
                                <p id="list"></p>

I am getting like this,

file1.txt file12.txt

but I was expecting output like this

file1.txt

file2.txt

please tell me where am wrong ?

why I am unable to create <li> dynamicall and is there any other way ?

It looks like you set the innerHTML inside the loop rather than outside. Also, output is an array, not a string.

(function() {
    "use strict";

    var files  = [{'name':'file1'}, {'name': 'file2'}],
        output = '',
        i;

    for (i = 0; i < files.length; i++) {
        output += '<li>' + files[i].name + '</li>';
    }

    document.getElementById('list').innerHTML = '<ul>' + output + '</ul>';
})();

jsFiddle

As gpojd mentions, your reseting the output is in the wrong loop and making it a string might be better. This works I think:

 <script type="text/javascript">
                    window.onload = function() {
                        var fileInput = document.getElementById('fileInput');
                        var output = "";

                        fileInput.addEventListener('change', function(e) {
                            var file1 = fileInput.files;

                            for(var i=0,f;f=file1[i];i++){
                                output += '<li>'+f.name+'</li>';
                                alert(f.name);
                                document.getElementById('list').innerHTML = '<ul>'+output+'</ul>';
                            }
                        });
                    }
                    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM