2015-02-08 24 views
3
<!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> 

我只是想知道爲什麼代碼不能正常工作,如果腳本部分從身體移動到頭部。爲什麼這隻在身體部分工作,而不在頭部

正確工作的代碼應該顯示文件名及其大小和其他詳細信息,但是當代碼被移動時,它不會顯示任何內容。

+2

您的良好起點應該打開瀏覽器控制檯,看看錯誤是什麼......這將是非常自我解釋。 – Fallup 2015-02-08 17:59:56

回答

7

因爲當你把它放在頭部時,files元素還不存在。所以當你打電話給document.getElementById('files')時,它會返回null,導致addEventListener亂放。

瀏覽器自上而下構建頁面。正因爲如此,最常見的情況是JavaScript放在最下面。

或者,您可以掛入DOMContentLoaded事件。這基本上是jQuery的$(document).ready()。或者做window.onload = function() {...}document.onload = function() {...}

但的確,把它放在底部更簡單。我通常只是這樣做。

+2

也可以使用'window.onload = function(){...}'或'document.onload'。 – giuscri 2015-02-08 18:03:33

+0

感謝它現在有道理。 – Cathal 2015-02-08 18:05:07

+0

感謝@giuscri我加入了 – 2015-02-08 18:07:22

相關問題