在没有自动关闭标记的元素之前和之后插入内容 [英] Insert Content Before and After an Element Without Autoclosing tags

查看:71
本文介绍了在没有自动关闭标记的元素之前和之后插入内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下内容:

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

我想在它之前插入一些东西**(注意未公开的div)**:

And I want to insert some stuff before it ** (notice the unclosed div)**:

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

还有一些**之后(注意我现在正在关闭div)**:

And some then some more after ** (notice I am now closing the div)**:

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

我想要的输出是:

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

相反,我得到的是:

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

因为jQuery会自动纠正未关闭的标签。

Because jQuery is automatically "correcting" the unclosed tags.

小提琴

fiddle

有没有办法使用.wrap()在元素之前和之后添加不同内容而不自动关闭标签?

Is there a way to use .wrap() to add different content before and after an element without automatically closing tags?

注意,我不能因为无关的限制而执行以下操作:

Note, I cannot do the following because of an unrelated restriction:

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


推荐答案

您不能插入部分或非封闭标签。在DOM中插入元素必须只插入整个元素。

You can't insert partial or unclosed tags. Inserting elements in the DOM must insert only whole elements.

您的选择是:


  1. 提取要包装在新元素中的元素,插入新容器对象,然后将原始元素放入容器中。

  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.

Mani直接填写父母的HTML(通常不推荐)。

Manipulate the HTML of a parent directly (generally not recommended).

使用jQuery .wrap()为你做#1选项的方法。有关jQuery的 .wrap()此处。 c>。

Use the jQuery .wrap() method which does the option in #1 for you. See here for more info on jQuery's .wrap().

这篇关于在没有自动关闭标记的元素之前和之后插入内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆