2017-04-05 34 views
0

我有以下代碼,它允許用戶選擇一個文本文件,然後它將內容加載到下面的PRE標記中。每隔10秒重新載入一次文本文件的內容

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
 
    <head> 
 
    <title>Load text file</title> 
 
    <script type="text/javascript"> 
 
\t \t function readText(that){ 
 
\t \t \t if(that.files && that.files[0]){ 
 
\t \t \t \t var reader = new FileReader(); 
 
\t \t \t \t reader.onload = function (e) { 
 
\t \t \t \t \t var contents = e.target.result;//.replace("\r\n","<br/>"); 
 
\t \t \t \t \t contents = contents.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); 
 
\t \t \t \t \t document.getElementById('board').innerHTML= contents; 
 
\t \t \t \t };//end onload() 
 
\t \t \t \t reader.readAsText(that.files[0]); 
 
\t \t \t }//end if html5 filelist support 
 
\t \t } 
 
    </script> 
 
    </head> 
 
    <body> 
 

 
<input type="file" onchange='readText(this)' /> <hr /> 
 

 
<pre id="board" contenteditable = "true"> 
 
This is where the text from the chosen text file will be loaded. 
 
</pre> 
 

 
</body> 
 
</html>

是否可以讀取所選擇的文件每10秒的內容是什麼?

例如,用戶選擇文本文件(一次)。 然後代碼循環並重新讀取內容並更新PRE標籤,並對文本文件進行任何更改。

我在本地工作,所以任何服務器腳本是不可能的。

我有一種感覺,解決方案可能涉及SETINTERVAL?

謝謝大衛。

+0

爲什麼不只是使用setInterval? –

+0

你能夠得到它的工作? – jmcall10

+1

您想要每10秒重新讀取上傳文件的內容,以便在其更改的情況下獲取其更新的內容? –

回答

0

您可以使用

// A variable to store the id of the setInterval method 
var currentIntervalId = undefined; 
// The function that calls your method. 
var startOrRestart = function(that) { 
    // Clear the 'old' calls to avoid wrong behavior 
    if (currentIntervalId !== undefined) clearInterval(currentIntervalId); 
    readText(that); // For executing immediately 
    // Execute it readText each 10 seconds 
    currentIntervalId = setInterval(function() { readText(that); }, 10000); 
}; 

,並在您輸入的標籤調用

<input type="file" onchange='startOrRestart(this)' /> 

這個解決方案的想法是,你執行一次你READTEXT(即)功能,後各10秒(藉助於setInverval函數)。但是,如果文本更改,則會再次執行setInterval函數。所以,你有一個處理'舊'輸入的舊'觸發器';並且你有一個新的輸入觸發器。爲了避免這種不希望的行爲,我們存儲觸發器的ID,並在設置時終止觸發器。

+0

嗨,感謝您的回覆。但是我無法讓這段代碼正常工作。你能提供更多的幫助嗎?謝謝 – jmcall10

+0

將JavaScript放在腳本標記中。此外,切換_onchange ='readText(this)'_ to _onchange ='startOrRestart(this)'_。有沒有失敗的輸出? – Guybrush

+0

確定最初我在身體內創建了一個新的腳本標記,但是我已將您的JS粘貼到原始腳本標記中並更改了onchange。這工作在鉻,但不是在IE或FF。 – jmcall10

相關問題