簡體   English   中英

准確獲取在文本框中寫入的文本

[英]Get exactly text that is write in textbox

我有一個用於編寫消息的文本框。 我想用 div 顯示寫在這個文本框中的文本。 我這樣做了,但只顯示文本,但格式化並不意味着當我使用 enter 編寫時,然后在預覽文本中相互顯示。 未顯示在下一行。

 function limiter(){ var tex = document.SendSms.msg.value; $(".speech").html(tex); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name='SendSms'> <textarea name="msg" id="msg" class="txtareabox" wrap='physical' onkeyup="limiter()" required ></textarea> <div id="mobilescreen"> <div id="mobiletext"> <p class="speech">See your preview here.. </p> </div> </div>

form標簽中的name屬性已被棄用,不應使用( 參見規范),而應使用id

function limiter() {
  var tex = $("#msg").val(); // get the value of the form input (textarea) and store it in tex variable
  $(".speech").html(tex); // set the value as innerHTML of the element(s) with 'speech' class
}

這是 ypur 問題的近似。 認為 textarea 中的 \\n 必須翻譯為"<br/>"

https://jsfiddle.net/qu0mcsd6/

這是js代碼:

function addText(){
    var tex = document.SendSms.msg.value;
  tex = tex.replace(/\n/g, "<br>");
  $(".speech").html(tex);
}
$('#poner').click(addText);

謝謝

您應該在返回值中用<br>替換\\n

document.SendSms.msg.value.replace(/\n/g,"<br>");

注意:由於您使用的是 jQuery,您可以在 js 代碼中定義事件,我建議使用input事件而不是keyup因為它在跟蹤用戶輸入時效率更高

$('#msg').on('input', function(){
    $(".speech").html( $(this).val().replace(/\n/g,"<br>") );
})

希望這可以幫助。

 $('#msg').on('input', function(){ $(".speech").html( $(this).val().replace(/\\n/g,"<br>") ); })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="SendSms"> <textarea name="msg" id="msg" class="txtareabox" wrap='physical' required ></textarea> and the div in which i want to show my preview: </form> <div id="mobilescreen"> <div id="mobiletext"> <p class="speech">See your preview here.. </p> </div> </div>

只需使用String.replace()將 \\r\\n 更改為<br> 這是你在 ES6 中的做法,只需使用 var 而不是 const 並讓向后兼容

 const textarea = document.querySelector("textarea"); const div = document.querySelector("div"); let text = textarea.innerHTML; text = text.replace(/\\r?\\n/g, '<br>'); div.innerHTML = text;
 <textarea> Line 1 line2 line3 </textarea> <div></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM