New lines in text within a div

偶尔善良 提交于 2020-07-06 05:50:21

问题


I have a little issue related to when I place a text loaded via ajax call.

I take the contect from a textarea and store it in my database and when I want to show the text in a div, it doesn't respect the new lines, so all the text is continuous.

The following code show a small example:

$(function() {
    $('.buttonA').click(function() {
        $('.message').html($('textarea[name="mensaje"]').val());
    });
});
.message {
    width:300px;
    height:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<textarea name="mensaje" class="new_message_textarea" placeholder="enter message..."></textarea>
<button class="buttonA">Enter</button>
<div class="message"></div>

If you type some text with some new lines, once you click on the button, the text is show into the div and will see that new lines are not show.

How can I solve this?


回答1:


Newline characters don't do any thing to html rendering. Change this in your js:

$('.message').html($('textarea[name="mensaje"]').val());

...to this:

$('.message').html($('textarea[name="mensaje"]').val().replace(/\n/g, "<br />"));

...and it will replace your newlines with a proper html line break




回答2:


I think a better way to achieve this is to add

white-space: pre

or

white-space: pre-wrap

style to your div. see HTML - Newline char in DIV content editable?




回答3:


Add this to the CSS:

white-space: pre-line


来源:https://stackoverflow.com/questions/11423300/new-lines-in-text-within-a-div

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