我正在将一个文本文件从外部目录导入到一个 html 段落标记中,以便在单击按钮时显示。我正在使用 jQuery 的 .load() 函数来执行此操作。
文本文件导入没有问题,但格式没有保留,
导入的文本文件“banks.txt”作为:
"Love Poem Serene, In a world full of troubles, i.e. doing nothing about it. - Iain Banks"
代替:
Love Poem
Serene,
In a world full of troubles,
i.e. doing nothing about it.
- Iain Banks
有没有办法保留文本文件的格式——换行符、制表符等等?
最佳答案
您应该将文本文件作为 pre
元素中的文本加载到 pre
标记中
以固定宽度的字体显示,并保留空格和
换行符。对 Internet Explorer 试试这个(它的行为不同;只需将文本文件加载到 pre
标记中,对于其他浏览器应该没问题):
$("#data pre").load("lorem.txt", function(response, status, xhr) {
if (status != "error") {
if (($.browser.msie)&&(jQuery.browser.version=="8.0"))//check if browser is Internet Explorer
$("#data pre").html(response.replace(/\r\n/g, "<br>"));//replace new lines with <br> tag
}
});
HTML:
<div id="data">
<pre></pre>
</div>
关于javascript - 使用 jQuery 的 .load() 函数保持导入的文本文件的格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51331062/