简体   繁体   English

使用div contentEditable innerText和innerHTML都没有到数据库的换行符

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

I'm using a div for people to enter text and then I tried saving 我正在使用div来输入文字,然后尝试保存

div.innerText

and

div.innerHTML

to my database but when I bring it back from the database and put it back into the div all of the carriage returns or newlines are gone 到我的数据库,但是当我从数据库中将其放回div并放回div中时,所有回车符或换行符都消失

innerHTML to database innerHTML到数据库

a

b

c

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

innerText to database innerText到数据库

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

if you could tell me how to handle this situation I would appreciate it greatly thank you for your time 如果您能告诉我如何处理这种情况,我将不胜感激,谢谢您的时间

div.innerHTML creates an HTML output of your new lines using <div> containers. div.innerHTML使用<div>容器创建新行的HTML输出。 Therefore the line breaks will be "replaced". 因此,换行符将被“替换”。

div.innerText uses the "invisible" character \\n or \\r\\n to mark new lines and it is possible that they are not shown in your database. div.innerText使用“不可见”字符\\n\\r\\n标记新行,并且可能未在数据库中显示它们。 You can however replace them by <br> tags to see if they are there. 但是,您可以将它们替换为<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>')); replaces all different kinds of possible new lines into <br> tags. 将所有可能的新行替换为<br>标签。

You can substitute <textarea> element for <div> with contenteditable attribute set. 您可以使用contenteditable属性集来替换<textarea> <div> <textarea>元素。 Encode, decode .value of textarea using encodeURIComponent() , decodeURIComponent() or format data as JSON utilizing JSON.stringify() , JSON.parse() 使用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