![](/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.