【问题标题】:How to read and display a text file in to a <pre>, preserving line breaks, tabs and new lines?如何在 <pre> 中读取和显示文本文件,保留换行符、制表符和换行符?
【发布时间】:2019-11-20 02:59:17
【问题描述】:

我正在尝试使用 jQuery 加载一个文本文件以显示在 pre 标记中。我想显示所有文本,包括换行符、制表符等转义序列。如果我使用jQuery.get('log.cpp', function(data) { ... 并尝试显示文本:

var str = data.replace(/(?:\r\n|\r|\n)/g, '<br>');
$('#fileName').html(str);

然后像&lt;&gt;这样的许多字符以及被这些字符包围的文本根本不显示。由于我尝试加载和显示一些源代码,带有#include &lt;header&gt; 的行将仅显示为#include。 如果我尝试使用以下内容:

var str = data.replace(/(?:\r\n|\r|\n)/g, '\n');
$('#fileName').text(str);

屏幕上不显示制表符或新行,文本仅显示为一行。

有什么提示吗? 非常感谢

【问题讨论】:

  • 摆脱replace() 调用,只使用text()。然后代码将正常工作。 jsfiddle.net/RoryMcCrossan/vsx8tucj
  • 非常感谢您的建议,这让我发现了错误:动态创建的html标签是“prev”而不是“pre”。

标签: jquery file text display formatted


【解决方案1】:

只需将其添加到您要阅读或显示的位置

style="white-space: unset;"

当你想阅读时

<textarea type="text" style="white-space: unset;"></textarea>

当你想显示时

<pre style="white-space: unset;">Your text with line breaks</pre>

【讨论】:

    猜你喜欢
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多