简体   繁体   English

在html textarea中按Enter时如何使用jquery添加换行符

[英]How would I use jquery to add a line break when pressing enter in a html textarea

I've been looking all over Google, and found some interesting ways to do this, but none of them hide the <br /> 我一直在Google各处搜索,找到了一些有趣的方法来实现此目的,但没有一个方法隐藏了<br />

I read that if I used \\n it wouldn't show up, but it does show up in the text field. 我读到如果使用\\n不会显示它,但是它确实显示在文本字段中。 I can always have something in the textarea and preg_replace it with <br /> later I suppose in my php that handles the form associated with the text area. 我总是可以在textarea中放一些东西,然后在<br />中用preg_replace替换它,我想在我的php中处理与文本区域关联的表单。

To clarify, I have a textarea that will need several line breaks to separate content. 为了澄清,我有一个文本区域,需要几个换行符才能分隔内容。 So I want a user to be able to press enter for a new line, and add a <br /> at the end of each line. 因此,我希望用户能够按Enter键换行,并在每行末尾添加<br /> But I do not want the <br /> or whatever I insert to replace later to be visible to the user. 但是我不希望<br />或稍后插入的任何内容对用户可见。

A good example is Facebook. 一个很好的例子是Facebook。 Facebook is very javascript heavy. Facebook的JavaScript非常丰富。 So much that you need to press shift + enter in order to get a new line so the form doesn't submit. 太多了,您需要按Shift + Enter以获得新行,因此该表单无法提交。 But when you enter text on two lines there is a line break inserted so the content displays on two lines and you never see the <br /> or whatever they use inside of the form when writing your post. 但是,当您在两行中输入文本时,会插入一个换行符,因此内容将显示在两行中,并且您在撰写文章时不会看到<br />或它们在表单中使用的任何内容。

How can I do this? 我怎样才能做到这一点?

I used the php nl2br function to convert \\n to <br /> 我使用php nl2br函数将\\ n转换为<br />

http://www.php.net/manual/en/function.nl2br.php http://www.php.net/manual/zh/function.nl2br.php

I like this method because it doesn't require anything extra. 我喜欢这种方法,因为它不需要任何额外的东西。 Just wrap nlbr2() around my variable and that is it. 只需将nlbr2()包裹在我的变量周围即可。 Php is all ready adding the \\n for me, just needed to convert it. PHP已经准备好为我添加\\ n,只需要对其进行转换。

use nl2br() before save the similar content. 在保存类似内容之前使用nl2br()。

http://www.php.net/manual/en/function.nl2br.php http://www.php.net/manual/zh/function.nl2br.php

$content = nl2br($content);

and save. 并保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM