jquery插入一个html块,以便它在目标之前开始并在目标之后结束 - 这可能吗?

发布于 2024-09-05 12:47:08 字数 455 浏览 2 评论 0原文

我知道您可以使用 before()insertBefore()after()在目标之前和之后添加插入 html 块>insertAfter()

我尝试做类似的事情

<script type="text/javascript">
    $(document).ready(function(){
        $("p").before("<div class='myContainer'>");
        $("p").after("</div>");
    });
</script>

<p>paragraph</p>

但是注入似乎会自动为我创建结束标签,有办法解决这个问题吗?

干杯

I understand you can add insert blocks of html before and after a target using before(), insertBefore(), after() and insertAfter().

I tried to do something similar to this

<script type="text/javascript">
    $(document).ready(function(){
        $("p").before("<div class='myContainer'>");
        $("p").after("</div>");
    });
</script>

<p>paragraph</p>

But the inject seems to automatically create closing tags for me, is there a way around this?

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心意如水 2024-09-12 12:47:08

有一个函数可以实现这一点:) 使用 .wrap(),例如this:

$("p").wrap("<div class='myContainer'>");

这将包装每个独立的

您可以在此处查看演示,它改变了这个:

<p>Paragraph 1</p>
<p>Paragraph 2</p>​

变成了这个:

<div class='myContainer'>
  <p>Paragraph 1</p>
</div>
<div class='myContainer'>
  <p>Paragraph 2</p>​
</div>

There's a function for that :) Use .wrap(), like this:

$("p").wrap("<div class='myContainer'>");

This will wrap each <p> independent, you can see a demo here, it changes this:

<p>Paragraph 1</p>
<p>Paragraph 2</p>​

Into this:

<div class='myContainer'>
  <p>Paragraph 1</p>
</div>
<div class='myContainer'>
  <p>Paragraph 2</p>​
</div>
一瞬间的火花 2024-09-12 12:47:08

只是提一下,您也可以这样做:

$myDiv = $("<div class='myContainer'></div>");
$("p").wrap($myDiv);

然后稍后再将内容附加到 myDiv 中

$myDiv.append("This is going to be the text in myContainer");

Just to mention you could also do:

$myDiv = $("<div class='myContainer'></div>");
$("p").wrap($myDiv);

and then again at a later time append stuff to myDiv with

$myDiv.append("This is going to be the text in myContainer");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文