如何加载包含html标签的.txt文件而不通过html解释它

How can I load a .txt file containing html tags without interpreting it by html?

本文关键字:html 文件 解释 txt 标签 何加载 加载 包含      更新时间:2023-09-26

当我使用FileReader()方法加载包含html标记的.txt文件并尝试在屏幕上显示它时,它显示了我已经解释的代码。这里有一个问题,因为我也需要这些标签,而不用html来解释它。例如:

file.txt中的一些文本
我想得到:
 <p>这样的文本在文件。txt与这些html标签</p> 

这里是我使用的代码:https://jsfiddle.net/fkwugnsn/。现在尝试加载一个包含html内容的txt文件。可以看到它已经被html解释过了。我不需要解释代码

插入createTextNodeappendChild(或replaceChild)的内容,而不是将其分配给innerHTML(我认为您正在这样做)。

var node = document.createTextNode(mytext);
someElement.appendChild(node);

你可以使用这个函数:

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

此函数将用html实体替换&, <, >"