的index.html
<!DOCTYPE html>
<html>
<head>
<title>Understanding File upload and File access Javascript</title>
</head>
<body>
<input type = "file" id = "files" name = "files[]" multiple></input>
<output id = "list"></output>
<script>
function handleFileSelect(evt){
var files = evt.target.files;
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>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
此示例完美无误,无错误。我收到错误 TypeError:document.getElementById(...)为null 如果我从js文件调用javascript函数。此代码如下。
的index.html
<!DOCTYPE html>
<html>
<head>
<title>Understanding File upload and File access Javascript</title>
<script src = "fileaccess.js" type = "text/javascript"></script>
</head>
<body>
<input type = "file" id = "files" name = "files[]" multiple></input>
<output id = "list"></output>
</body>
</html>
index.js
function handleFileSelect(evt){
var files = evt.target.files;
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>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
现在,这两个例子有什么不同。如果我在html页面中调用javascript函数,我不明白为什么我会收到错误。
答案 0 :(得分:1)
区别在于脚本的位置
在第一个示例中,脚本标记在之后中的元素,在第二个示例中,脚本标记位于头部,之前 DOM中的元素。< / p>
为了能够使用.getElementById
以及任何其他此类方法获取元素,必须首先加载元素 ,这意味着脚本必须在DOM中的元素,或者脚本需要使用事件处理程序来等待加载页面,例如window.onload
,DOMContentLoaded
等。<!DOCTYPE html>
<html>
<head>
<title>Understanding File upload and File access Javascript</title>
</head>
<body>
<input type = "file" id = "files" name = "files[]" multiple></input>
<output id = "list"></output>
<script src = "fileaccess.js" type = "text/javascript"></script>
</body>
</html>