簡體   English   中英

使用div contentEditable innerText和innerHTML都沒有到數據庫的換行符

[英]using a div contentEditable innerText and innerHTML neither have newlines to and from database

我正在使用div來輸入文字,然后嘗試保存

div.innerText

div.innerHTML

到我的數據庫,但是當我從數據庫中將其放回div並放回div中時,所有回車符或換行符都消失

innerHTML到數據庫

a

b

c

    //in database like this  <div>a</div><div></div><div>b</div><div></div><div>c</div>

innerText到數據庫

a
a
a
a
a
a
    //how it stored in database  aaaaaa

如果您能告訴我如何處理這種情況,我將不勝感激,謝謝您的時間

div.innerHTML使用<div>容器創建新行的HTML輸出。 因此,換行符將被“替換”。

div.innerText使用“不可見”字符\\n\\r\\n標記新行,並且可能未在數據庫中顯示它們。 但是,您可以將它們替換為<br>標記,以查看它們是否在那里。

 document.getElementById("output").addEventListener("click", function() { console.log("HTML:"); console.log(document.getElementById("text").innerHTML); console.log("Text:"); var text = document.getElementById("text").innerText; console.log(text.replace(/(?:\\r\\n|\\r|\\n)/g, '<br>')); }); 
 #text { background-color:#FAFAFA; border: red solid 1px; height:150px; width: 200px; } 
 <button id="output"> Show in console </button> <div id="text" contenteditable> </div> 

console.log(text.replace(/(?:\\r\\n|\\r|\\n)/g, '<br>')); 將所有可能的新行替換為<br>標簽。

您可以使用contenteditable屬性集來替換<textarea> <div> <textarea>元素。 使用encodeURIComponent()decodeURIComponent()編碼,解碼textarea .value或使用JSON.stringify()JSON.parse()數據格式化為JSON

 var button = document.querySelector("button") var textarea = document.querySelector("textarea"); button.onclick = function() { var value = textarea.value console.log(encodeURIComponent(value) , decodeURIComponent(value) , JSON.stringify(value) , JSON.parse(JSON.stringify(value)) ); } 
 textarea { border: 1px solid navy; width: 300px; height: 200px; } You can use 
 <button>click</button><br> <textarea></textarea> 

暫無
暫無

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

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