繁体   English   中英

来自txt的Javascript数组并将其打印在本地html上

[英]Javascript array from txt and print it on local html

我的 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 
...

第一个示例中的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 onerror="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}>` } )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM