jquery 在输入时添加换行符或换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7338820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:43:48  来源:igfitidea点击:

jquery add newline or linebreak on enter

jquery

提问by David

I have a simple textarea. Is it possible with jquery to add a 'br' when I hit the enter button? I've read around here, and the only solution I see is to add a linebreak at the very end of the val().

我有一个简单的文本区域。当我按下回车按钮时,jquery 是否可以添加一个“br”?我已经阅读了这里,我看到的唯一解决方案是在 val() 的最后添加一个换行符。

But I need it to work on every enter press.

但我需要它在每次输入新闻上工作。

回答by Jamie Dixon

You can simply split on the line feed:

您可以简单地在换行符上拆分:

var content = $('#myTextBox').val();
var contentArray = content.split(/\n/);

and then spit each one out as a paragraph:

然后把每一个都作为一个段落吐出来:

$.each(contentArray, function(){
   $('#previewArea').append('<p>' + this + '</p>');
});

If you're just wanting to put the result into a database as you've stated, you can do the same but build it into a string for insersion:

如果您只是想将结果放入您所说的数据库中,您可以执行相同的操作,但将其构建为插入的字符串:

var myOutputVar;
$.each(contentArray, function(){
   myOutputVar += this + '<br />';
});

Based on your comments it looks like you just need the br added when you insert the data into your database. I'm assuming that you're doing this with an ajax post since you've tagged this as a jQuery question.

根据您的评论,您似乎只需要在将数据插入数据库时​​添加 br。我假设您正在使用 ajax 帖子执行此操作,因为您已将其标记为 jQuery 问题。

Either way, you can just send your data to the server and split it up there using your server side language of choice.

无论哪种方式,您都可以将数据发送到服务器并使用您选择的服务器端语言将其拆分。

回答by Andy

meh, it's ok if it doesn't show it. I just need each new line to have a br added for when it gets added to the database

嗯,不显示也没关系。我只需要在每个新行添加到数据库时添加一个 br

if you're using php you can use nl2brto change the newlines to BRs

如果您使用的是 php,则可以使用nl2br将换行符更改为BR

alternately you could add extra BRs on enter directly in the textarea: http://jsfiddle.net/F9XZN/

或者,您可以在 textarea 中直接输入时添加额外的 BR:http: //jsfiddle.net/F9XZN/

回答by Meenakshi

try this

尝试这个

$('#textareaid').bind('keypress', function(e) {
        if(e.keyCode==13){
                // Enter pressed... do anything here...
                   $(this).val(  $(this).val() + "<br/>");


        }
});