简体   繁体   English

创建一个 <div> 在里面 <p> 动态

[英]Creating a <div> inside a <p> dynamically

I'm trying to create a div inside ap with a click function. 我正在尝试使用单击功能在ap内创建一个div。 But it seems not to close my p element. 但似乎没有关闭我的p元素。 Apparently after reading this , it seems that if the p element is immediately followed by a div in this case it doesn't require a closing tag at the end. 显然,看完后 ,似乎如果P元素紧跟在这种情况下,一个div它不需要在年底关闭标签。

<div class="main"></div>
<div class="content-list"><ul class="information"> </ul></div>

I'm going to append to the with this function: 我将使用此函数追加到:

var $contentHandler = $(".content-list");
var $mainHandler = $(".main");
var $infoHandler = $(".information");
var circleCounter = 1;



$mainHandler.click(function() {
    var htmlString = "<li class='" + circleCounter + "'> <p class='circle-color'> var   color = <div class='circle-color-input' contentEditable autocorrect='off'> type a color</div> ; </p> <p class='circle-radius'> </p> <p class='circle'> </p> </li>"
    $infoHandler.append(htmlString);
    circleCounter++;


});

Here is the code for that 这是代码

http://jsfiddle.net/mauricioSanchez/tJkex/ http://jsfiddle.net/mauricioSanchez/tJkex/

Is there any way around this? 有没有办法解决?

Thanks! 谢谢!

You quite simply cannot have a div inside a p , because the only kind of content allowed in a p element is phrasing content (as stated in the document you've read), which usually means inline elements. 你很简单, p 不能div ,因为p元素中允许的唯一内容是短语内容(如你所阅读的文档中所述),这通常意味着内联元素。 That's why having a div (or any other flow element such as ul or figure ) immediately following an unclosed p will implicitly close that p and be created as a sibling, not a child, in the DOM. 这就是为什么在未关闭的p紧跟一个div (或任何其他流元素,如ulfigure )将隐式关闭该p并在DOM中创建为兄弟,而不是子元素。

You can use a span instead and make it display as a block if needed: 您可以使用span并在需要时将其显示为块:

var htmlString = "<li class='" + circleCounter + "'> <p class='circle-color'> var   color = <span class='circle-color-input' contentEditable autocorrect='off'> type a color</span> ; </p> <p class='circle-radius'> </p> <p class='circle'> </p> </li>"

div is not allowed to be inside p , see Why <p> tag can't contain <div> tag inside it? div不允许在p里面,看看为什么<p>标签里面不能包含<div>标签呢?

The browser think you forgot to enclose the p tag, so it implicitly adds a closing tag before div . 浏览器认为您忘记将p标记括起来,因此它会在div之前隐式添加结束标记。

我想你想要css属性溢出:滚动?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM