Paste

closing tag without spawning an opening

2019-08-29 11:12发布

问题:

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.