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

时间:2016-10-30 22:37:41

标签: javascript html string html5 contenteditable

我使用div来让人们输入文字,然后我尝试保存

div.innerText

div.innerHTML

到我的数据库,但是当我从数据库中将其带回并将其放回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

如果你能告诉我如何处理这种情况,我将非常感谢你的时间

2 个答案:

答案 0 :(得分:1)

std::function使用div.innerHTML容器为新行创建HTML输出。 因此,换行符将被“替换”。

<div>使用“隐身”字符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>'));标记。

答案 1 :(得分:0)

您可以将<textarea>元素替换为<div>属性集contenteditable。使用encodeURIComponent().valuetextarea decodeURIComponent()进行编码,解码,或使用JSON.stringify()格式化数据JSONJSON.parse()

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>