为什么document.getElementById('files')返回null?

时间:2012-07-04 02:56:09

标签: javascript html5

以下代码根本无效。

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

由firebug报告此getElementById为null但我添加了一个文本,它正在工作.....

似乎代码是正确的......

更新:这是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>

1 个答案:

答案 0 :(得分:7)

那是因为你正在尝试获取一个元素,而元素本身尚未加载。您需要在元素之后向下移动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);