简体   繁体   English

在没有自动关闭标记的元素之前和之后插入内容

[英]Insert Content Before and After an Element Without Autoclosing tags

Say I have the following: 说我有以下内容:

<div id="content">content</div>

And I want to insert some stuff before it ** (notice the unclosed div)**: 我想在它之前插入一些东西**(注意未公开的div)**:

$("#content").before("<div>pre-pre-content</div><div>pre-content ");

And some then some more after ** (notice I am now closing the div)**: **之后会有一些更多(注意我现在正在关闭div)**:

$("#content").after(" post-content</div><div>post-post-content</div>");

My desired output is: 我想要的输出是:

<div>pre-pre content</div>
<div>
    pre-content <div id="content">content</div> post-content
</div>
<div>post-post content</div>

Instead, what I get is: 相反,我得到的是:

<div>pre-pre content</div>
<div>pre-content</div>
<div id="content">content</div>
<div>post-content</div>
<div>post-post content</div>

Because jQuery is automatically "correcting" the unclosed tags. 因为jQuery会自动“纠正”未关闭的标签。

fiddle 小提琴

Is there a way to use .wrap() to add different content before and after an element without automatically closing tags? 有没有办法使用.wrap()在元素之前和之后添加不同的内容而不自动关闭标签?

Note, I cannot do the following because of an unrelated restriction: 请注意,由于不相关的限制,我无法执行以下操作:

$("#content").html("<div>Content before " + $("#content).html() + " Content after</div>")

You can't insert partial or unclosed tags. 您无法插入部分或未封闭的标签。 Inserting elements in the DOM must insert only whole elements. 在DOM中插入元素必须只插入整个元素。

Your choices are: 你的选择是:

  1. Extract the element you want to be wrapped in your new element, insert the new container object and then put your original element into the container. 提取要在新元素中包装的元素,插入新的容器对象,然后将原始元素放入容器中。

  2. Manipulate the HTML of a parent directly (generally not recommended). 直接操作父级的HTML(通常不推荐)。

  3. Use the jQuery .wrap() method which does the option in #1 for you. 使用jQuery .wrap()方法为您执行#1中的选项。 See here for more info on jQuery's .wrap() . 有关jQuery的.wrap()更多信息,请参见此处

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

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