简体   繁体   English

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

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

I have a problem with javascript code.我的 javascript 代码有问题。 I have to make local html which displays lines of text from .txt file.我必须制作本地 html,它显示 .txt 文件中的文本行。 I found a code like this, which does it:我找到了这样的代码,它可以做到:

 <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>

However, I need those to be displayed like in this code:但是,我需要像以下代码一样显示这些内容:

<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>

No matter how I try to combine this two, it doesnt seem to work (nothing gets displayed at all).无论我如何尝试将这两者结合起来,它似乎都不起作用(根本没有显示任何内容)。 I am rather green with regards to javascirpt, so could someone help me with that and, if possible, explain in rather simple language how is that supposed to be done?我对 javascipt 比较陌生,所以有人可以帮我解决这个问题,如果可能的话,用相当简单的语言解释应该怎么做?

.txt file would look something like: .txt 文件类似于:

Position1
description1 
position2 
description2 
pozition3 
...

Your reader.result in the first example is a single multi-line string.第一个示例中的reader.result是单个多行字符串。 For your second snippet to work, you need an array of strings, one-per-line.要使您的第二个代码段起作用,您需要一个字符串数组,每行一个。

Here's how you can split your multi-line text file in to an array of lines:以下是将多行文本文件拆分为行数组的方法:

 const txtFile = `Position1 description1 position2 description2 pozition3`; const lines = txtFile.split("\\n"); console.log(lines);

Once you have these lines, you can proceed as you already showed.一旦你有了这些行,你就可以像你已经展示的那样继续了。 One warning: by using innerHTML you run in to the risk of injecting stuff in to your document you might not want.一个警告:通过使用innerHTML ,您可能会面临向文档中注入您可能不想要的内容的风险。 In most cases, it's better to construct the HTML elements in code and use innerText :在大多数情况下,最好在代码中构造 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