我想在不克隆 HTML 檔案的情況下制作一個簡單的網站。
我想將內容存盤在子目錄(例如 pages/pagehome.txt、pages/pageabout.txt、pages/pagecontact.txt)中的單獨文本檔案(或 html)中。我使用了標簽,但它不允許為嵌入的內容重用 css。
我想將該檔案匯入變數并通過 innerHTML 標記更改 div。如何將內容從該檔案??匯入變數?我不想使用任何復雜的 API 或大量代碼。
是否有僅使用 JS 將檔案內容加載到變數的簡單方法(沒有 HTML 或帶有內容的不可見 div 之類的方法)?
uj5u.com熱心網友回復:
使用XMLHttpRequest, 并使用onload回呼來獲取回應。
<body>
<div id="divv"></div>
<script>
var txtFile = new XMLHttpRequest();
txtFile.onload = function(e) {
document.getElementById("divv").innerHTML = txtFile.responseText;
}
txtFile.open("GET", "file.txt", true);
txtFile.send(null);
</script>
</body>
編輯:看來你需要訪問本地檔案,所以你可以使用這樣的東西
<body>
<div id="divv"></div>
<script>
window.onload = function() {
var iframe = document.createElement('iframe');
iframe.id = 'iframe';
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = 'file.txt';
iframe.onload = function(){
var text = document.getElementById('iframe').contentDocument.body.firstChild.innerHTML;
document.getElementById('divv').innerHTML = text;
};
}
</script>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/413525.html
標籤:
上一篇:從html開始的麻煩。無法在瀏覽器中打開新的html檔案
下一篇:如何從頭開始列印一行?
