Paste </p> closing tag without spawning an opening p tag in contenteditable

流过昼夜 提交于 2019-12-25 18:30:31

问题


I've got a contenteditable div:

<div id="result" class="content" contenteditable="true"><p><br/></p></div>

I want new paragraphs to form when I press ENTER, and for that I intercept ENTER keydown and replace the default action by the insertion of a html code:

$(".content").on("keydown",function(e){if(e.which == 13) { e.preventDefault(); pasteHtmlAtCaret("</p><p><br/>");}});

My hope was that when I press ENTER, the </p><p><br/> would close the existing paragraph and open a new paragraph. So, if I typed: 'hello world' + ENTER, I should have:

<p>hello world</p><p><br/></p>

where you can recognize the </p><p><br/> piece. I observe a different behaviour though. I get:

<p>hello world<p></p><p><br></p></p>

So it seems that the first</p> has spawned an opening <p> tag and that the <p> just before the <br/> tag has spawned a matching closing p tag. Does that mean that my browser ignores the existence of a wrapping <p></p>? How can I avoid the spawning a new p tags when I insert my little piece of html code?

I'm using Chromium and jQuery 1.7.2.


回答1:


Editing occurs in a document object model (DOM). The HTML tags don't really exist in the editor. The HTML is parsed into a DOM. The HTML tags are produced again when the DOM is serialized. Therefore, improper HTML fragments cannot be pasted without consequences.



来源:https://stackoverflow.com/questions/13431323/paste-p-closing-tag-without-spawning-an-opening-p-tag-in-contenteditable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!