为什么这只适用于body部分而不是头部


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<input type="file" id="files" multiple />
<label id="list"></label>
<script>
//Interact with local files using the HTML5 file API
function handleFileSelect(evt) 
{
    //target is the element that triggered the event
    var files = evt.target.files; // FileList object
    // files is a FileList of File objects. List some properties.
    for(var i=0; i<files.length; i++)
    {
        f = files[i];
        document.getElementById('list').innerHTML += f.name + ' ' + f.type + ' ' + f.size + ' bytes ' + f.lastModifiedDate + '<br/>';
    }
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>

我只是想知道如果脚本部分从正文移动到头部,为什么代码无法正常工作。

正常工作的代码应显示文件名及其大小和其他详细信息,但是当移动代码时,它不会显示任何这些内容。

因为当你把它放在头部时,files 元素还不存在。所以当你调用document.getElementById('files')时,它会返回null,导致addEventListener废话。

浏览器自上而下构建页面。最常见的是,你把JavaScript放在底部,因为这个。

或者,您可以挂钩到DOMContentLoaded事件。这基本上就是jQuery的$(document).ready()所做的。或者做window.onload = function() {...}document.onload = function() {...}.

但实际上,将其放在底部更简单。我通常只是这样做。

最新更新