[英].replace() of newline doesn't work with a contenteditable item
I have this simple code: 我有这个简单的代码:
<div style="margin-left:10px;">
<p>
<a class="btn" href="#" onclick="myFunction()"><i class="icon-link"></i></a>
</p>
</div>
<div style="margin-left:10px;">
<div id="example-one" >
<p id="textEditor" contenteditable="true"></p>
</div>
</div>
<script type="text/javascript">
function myFunction()
{
// removes <div> from #textEdtor's content
$("#textEditor>div").replaceWith(function() { return $(this).contents(); });
var str=document.getElementById("textEditor").innerHTML;
var n=str.replace(/\n|\r/g, '<br>')
document.getElementById("textEditor").innerHTML=n;
alert(n);
}
</script>
The problem is that the var n=str.replace(/\\n|\\r/g, '<br>')
doesn't work when user press enter. 问题是当用户按Enter键时,
var n=str.replace(/\\n|\\r/g, '<br>')
不起作用。 Although it works very well if i use this .replace(/\\[b\\]/g,'<b>').replace(/\\[\\/b\\]/g,'</b>')
虽然如果我使用这个
.replace(/\\[b\\]/g,'<b>').replace(/\\[\\/b\\]/g,'</b>')
效果很好
It only adds a <br>
only if you press twice the enter. 仅在按两次Enter键时,才会添加
<br>
。
Is there any way to fix this issue ? 有什么办法可以解决此问题?
Thank you. 谢谢。
The problem is in removing child <div>
elements. 问题在于删除子
<div>
元素。 Replace your code with the one below, and everything should work fine: 将您的代码替换为下面的代码,一切都会正常运行:
function myFunction() {
$("#textEditor > div").before("<br />").contents().unwrap();
}
DEMO: http://jsfiddle.net/Hm7DY/ 演示: http : //jsfiddle.net/Hm7DY/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.