How to preserve newlines when showing a text file with jQuery

◇◆丶佛笑我妖孽 提交于 2019-11-30 08:16:28

问题


I want to fetch the content of an text file and I have manage to do that. Everything is working except for one thing - detecting new lines.

My solution to fetch the content in the text file:

$.ajax({
    url: '/nhagyavi/files/textfiles/changelog.txt',
    success: function(data) {
        $('#load-changelog').html('<div style="font-family: Courier New;">' + data + '</div>');
    }
});

The content of the text file:

2012-03-15: Snabbfixar
- Detta är en fin liten rad som berättar vad som är nytt
- En till rad, tillsammans med en <a href="javascript:void(0)">länk</a>

How the result looks like on my page:

2012-03-15: Snabbfixar - Detta är en fin liten rad som berättar vad som är nytt - En till rad, tillsammans med en länk

I don't know how I can use print_r in jQuery so I can't really see how the lines really looks like. Anyone who knows how I can fix my problem?


回答1:


Add white-space:pre-line; to your container:

#load-changelog {
    white-space: pre-line;
}

Simplified demo: http://jsfiddle.net/tF3Mb/1/

If you also want to show all space characters, use white-space:pre instead of pre-line: http://jsfiddle.net/tF3Mb/



来源:https://stackoverflow.com/questions/9726970/how-to-preserve-newlines-when-showing-a-text-file-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!