![](/img/trans.png)
[英]How to remove line at the bottom of textarea while using CodeMirror text editor?
[英]How can I remove the empty line break at the bottom of my textarea after appending text using jQuery?
这可能是一个非常基本的问题,因为我希望在这里看起来不是那么疯狂-我一直在寻找一些现有的答案或更好的解决方案,因此,如果这是重复!
我的问题关于将数据append()添加到现有textarea元素:
jSFiddle : https : //jsfiddle.net/natureminded/7w3rmggp/
我的HTML :
<textarea id='chat'></textarea>
我的JS / jQuery :
//note: 'chatMsg' data is provided back from the server
$('#chat').append(chatMsg.name+': '+chatMsg.message+' ');
$('#chat').scrollTop($('#chat')[0].scrollHeight); // focuses on bottom of textarea
我想要的输出 :新行添加到textarea,每条新消息都作为新行。 texarea底部没有多余的线条。
我正在经历的是 :实际上,新行附加到了textarea上,每行都作为新行(由于使用了
HTML回车符)。 但是,由于此换行符位于我的append()
字符串的末尾,因此在我的最后一条消息下方添加了空行(请参见: https : //biturl.io/VCjaj5以获取屏幕截图)。 将回车符添加到字符串的开头将在底部固定额外的换行符,但是在发送第一条消息时将在最上方创建换行符。
我知道解决此问题的另一种方法是抓取$('#chat')
的.val()
$('#chat')
,然后将新数据添加为新行,例如:
var oldChat = $('#chat').val();
var newChat = oldChat + ' ' + chatMsg.name + ': ' + chatMsg.message;
$('#chat').val(newChat);
但是,当我尝试这种方法时,希望将新消息作为新行添加到oldChat
下方,因此不会显示HTMl托架字符,而是显示为文本(请参阅: https : oldChat
)。 我也尝试使用\\n
字符,但这实际上杀死了我的JavaScript prompt
(未显示),并且聊天中断了。
有什么更好的方法可以在聊天中添加新行,而又不会在底部增加额外的空白?
注意 :我想到的另一种可能的解决方案是尝试以某种方式使用正则表达式来抓住最后一行并将其删除,但是我想我会问这里是否有更简单的方法来执行此操作,或者我是否过于挑剔我的textarea可以很好且干净地附加文本(没有多余的换行符)。
您可以在换行符之前而不是之后,并且为了确保第一行上方没有新行,请检查textarea是否为空。
因此(此处为伪代码,但希望您能理解)
string = chatmessage
// Prepend newline to string if the textarea already contains content
if textarea.value.length !== 0
string = ' ' + string
textarea.value = string
尝试这个:
var strt = $('#chat').text().replace(/[\s\r\n\t]/g,"").length == 0 ? "" : "
";
$('#chat').append(strt + chatMsg.name+': '+chatMsg.message);
场景 :检测是否#chat
有消息附加break line + message
如果#chat
没有追加唯一的消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.