[英]Can't remove empty line break in textarea with Javascript replace method
[英]Remove line break from textarea
我有這樣的textarea:
<textarea tabindex="1" maxlength='2000' id="area"></textarea>
我用jquery看這個textarea:
$("#area").keypress(function (e) {
if (e.keyCode != 13) return;
var msg = $("#area").val().replace("\n", "");
if (!util.isBlank(msg))
{
send(msg);
$("#area").val("");
}
});
如果按下返回鍵並且消息不是空白或僅包含行間距,send()會將消息提交給服務器。
問題:發送消息后,textarea不會被清除。 在第一頁加載時,textarea為空。 提交消息后,textarea中有一個空行,我不知道如何擺脫它。
問題是Enter按鍵沒有被抑制,並且正在執行其通常的瀏覽器行為(即添加換行符)。 將return false
添加到keypress處理程序的末尾以防止這種情況發生。
$("#area").keypress(function (e) {
if (e.keyCode != 13) return;
var msg = $("#area").val().replace(/\n/g, "");
if (!util.isBlank(msg))
{
send(msg);
$("#area").val("");
}
return false;
});
托馬斯,e.preventDefault(); 將需要包含在條件內,僅將其應用於回車鍵。
// Restrict ENTER.
if (e.keyCode == '13') { e.preventDefault(); }
整個函數看起來像這樣(帶注釋):
// Key Press Listener Attachment for #area.
$("#area").keypress( function (event) {
// If the key code is not associated with the ENTER key...
if (event.keyCode != 13) {
// ...exit the function.
return false;
} else {
// Otherwise prevent the default event.
event.preventDefault();
// Get the message value, stripping any newline characters.
var msg = $("#area").val().replace("\n", "");
// If the message is not blank now...
if (!util.isBlank(msg)) {
// ...send the message.
send(msg);
// Clear the text area.
$("#area").val("");
}
}
} );
您將需要使用event.preventDefault()函數來防止發生默認事件操作,在這種情況下添加輸入字符:
$("#area").keypress(function (e) {
e.preventDefault();
if (e.keyCode != 13) return;
var msg = $("#area").val().replace("\n", "");
if (!util.isBlank(msg))
{
send(msg);
$("#area").val("");
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.