我的 javascript 代碼有問題。我必須制作本地 html,它顯示 .txt 檔案中的文本行。我找到了這樣的代碼,它可以做到:
<script>
var fileInput = document.getElementById('inputfile');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('output').innerText = reader.result;
};
reader.readAsText(file);
});
</script>
但是,我需要像以下代碼一樣顯示這些內容:
<script type="text/javascript">
var arr = ['Heading 1','Para1','Heading 2','Para2','Heading 3','Para3'];
var result = arr.map((val, i) => i%2===0 ? `<h2>${val}</h2>` : `<p>${val}</p>`).join('');
document.getElementById('test').innerHTML = result ;
</script>
無論我如何嘗試將這兩者結合起來,它似乎都不起作用(根本沒有顯示任何內容)。我對 javascipt 比較陌生,所以有人可以幫我解決這個問題,如果可能的話,用相當簡單的語言解釋應該怎么做?
.txt 檔案類似于:
Position1
description1
position2
description2
pozition3
...
uj5u.com熱心網友回復:
您reader.result在第一個示例中是單個多行字串。要使您的第二個代碼段起作用,您需要一個字串陣列,每行一個。
以下是將多行文本檔案拆分為行陣列的方法:
const txtFile = `Position1
description1
position2
description2
pozition3`;
const lines = txtFile.split("\n");
console.log(lines);
一旦你有了這些行,你就可以像你已經展示的那樣繼續了。一個警告:通過使用innerHTML,您可能會面臨向檔案中注入您可能不想要的內容的風險。在大多數情況下,最好在代碼中構造 HTML 元素并使用innerText:
const txt = `Hello
This is a paragraph
Heading
Injected scripts! <img src=x one rror="console.log(1234)">`;
const lines = txt.split("\n");
// "Safe" approach: display contents as text
// This will _not_ log 1234
lines.forEach(
(content, i) => {
const el = document.createElement(i % 2 === 0 ? "h2" : "p");
el.innerText = content;
document.body.appendChild(el);
}
);
// "Unsafe" approach: use innerHTML
// This _will_ log 1234
lines.forEach(
(content, i) => {
const tag = i % 2 === 0 ? "h2" : "p";
document.body.innerHTML = `<${tag}>${content}</${tag}>`
}
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/315975.html
標籤:javascript 数组
