jQuery:在 <textarea> 中保留用户输入的换行符

jQuery: Preserve user-inputted line breaks in <textarea>

我已经搜索 Google 和 SO 几个小时了,但似乎无法为我的生活找到答案!

我想做的就是保留用户在 <textarea> 元素中输入的换行符,通过 a jQuery [=post 内容14=]呼叫。如果我像往常一样简单地将表单提交到一个页面,这是有效的,但我的老板告诉我使用 REST/AJAX.

很多很多 post 在 SO 和网络上一般提到用 <br /> 替换 \n,或者在元素的 white-space: pre-wrap; 中使用 white-space: pre-wrap; CSS。这些解决方案 对我有用,因为换行符根本不会出现在 Chrome 开发人员工具中。

代码片段:

<form id="addPostForm" role="form" method="post" action="/blog">
    <div class="form-group">
        <textarea rows="5" id="postBody" name="postBody"></textarea>
        ...more input controls
    </div>
    <button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<script type="text/javascript">
    $(document).on('submit', '#addPostForm', function() {
        var postBody = $(this)[0].postBody.value;
        ...more code
    });
</script>

当我输入例如:

"这是第一段。

还有一个。

还有一个。

postBody 变量的值为:

"This is the first paragraph. And here is another. And yet another."

这让我发疯!当然这不应该像看起来那么难!

P.S。我认为这不会有什么不同,但以防万一有人想知道,我在这个项目中使用 Python/Pyramid、Jinja2 和 Bootstrap 3。

在 JS 中使用这个

$("input[type=submit]").click(function(){
  $.ajax({
   type: "POST",
   url: "yoururl",
   data: $("#addPostForm").serialize()
   (...)
  });
});

在您的服务器端代码中,您可以获得 POST 带有原始空格的值 postBody。

在我看来,这个问题源于 Chrome 开发工具去除了换行符。更改工具设置,或尝试其他方法,例如 firebug.

抱歉浪费您的时间,使用 $('#postBody').val() 而不是 $(this)[0].postBody.value 很简单。无论如何感谢所有评论者和回答者!

尝试用“\n”拆分行(是的,我已经测试过了),然后用
标签重新加入它们,检查一下:

$('textarea').val().split('\n')

将其放入您的 onclick 函数中,如果您正在使用 Chrome,则在其上设置一个断点,它将行拆分为一个数组。如果你加入

.join('<br>')

你应该可以开始了。