div内文本中的新行 [英] New lines in text within a div

查看:85
本文介绍了div内文本中的新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我放置通过ajax调用加载的文本时,我有一个小问题.

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

我从文本区域中获取该内容并将其存储在数据库中,并且当我想在div中显示文本时,它不遵守换行符,因此所有文本都是连续的.

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>

如果您键入带有一些新行的文本,则单击按钮后,该文本将显示在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.

我该如何解决?

推荐答案

换行符对html渲染没有任何作用.在您的js中更改它:

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

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

...对此:

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

...,它将用适当的html换行符替换您的换行符

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

这篇关于div内文本中的新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆