1

下面的代码根本不起作用。

document.getElementById('files').addEventListener('change', handleFileSelect, false);

萤火虫报告此 getElementById 为空,但我添加了一个文本,它正在工作.....

看来代码是正确的...

更新:这是 html 页面

<script type="text/javascript">

   document.getElementById('files').addEventListener('change', handleFileSelect,   false);
   document.getElementById('username');
   function handleFileSelect(evt) {
   alert('i am called');
   var files = evt.target.files; // FileList object

 // files is a FileList of File objects. List some properties.
 var output = [];
 for (var i = 0, f; f = files[i]; i++) {
  output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
              f.size, ' bytes, last modified: ',
              f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
              '</li>');}
  document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';}
</script>
</head>
<body>
<form>
<input type="text" id="username" />
<input type="file" id="files"  />
<div id="list"></div>
</form>
</body>
</html>
4

1 回答 1

8

那是因为您正在尝试获取一个元素,而元素本身尚未加载。您需要将 JavaScript 向下移动到元素之后,或者在页面完成加载后将代码作为回调运行。

document.addEventListener('DOMContentLoaded', function(){
    document.getElementById('files').addEventListener('change', handleFileSelect, false);
    document.getElementById('username');
    function handleFileSelect(evt) {

        alert('i am called');

        var files = evt.target.files; // FileList object

        // files is a FileList of File objects. List some properties.
        var output = [];
        for (var i = 0, f; f = files[i]; i++) {
            output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
            f.size, ' bytes, last modified: ',
            f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
              '</li>');
        }
        document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
    }
}, false);
于 2012-07-04T03:15:45.583 回答