gpt4 book ai didi

javascript - Jquery .insertBefore 忽略结束标签并自动关闭丢失的标签

转载 作者:行者123 更新时间:2023-11-30 16:29:17 24 4
gpt4 key购买 nike

我尝试将名为“foo”的 div 拆分为两个 div,方法是关闭第一个 div,然后使用 .insertBefore 打开一个具有相同类的新 div。但是 jquery 将忽略 div 结束标记并使用缺少的结束标记自动完成 div。

$( '</div><div class="foo">' ).insertBefore( 'h2:first' );

我明白了:

<div class="foo"></div>
<h2>Title</h2>

但是想要完成这个:

</div><div class="foo">
<h2>Title</h2>

我试图将一个名为“foo”的 div 拆分为两个 div,方法是关闭现有的 div,然后添加一个新的开始标记,这将导致两个 div 的“foo”。

有什么解决办法吗?

完整的 html 结构:(我想将它拆分成更小的“foo” block 几次。“foo”的所有内容都来自数据库,除了使用 jquery/js 之外我无法操作它。

<div class="foo">
<span>Text here</span>
<h2>Title</h2>
<p>Text</p>
<h2>Title</h2>
<p>Text</p>
<h2>Title</h2>
<p>Text</p>
<h3>Another title</h3>
<h2>Title</h2>
<p>Text</p>
<h2>Title</h2>
<p>Text</p>
<h3>Another title</h3>
<h2>Title</h2>
<p>Text</p>
</div>

最佳答案

这会将以第一个 h2 开头的所有内容移动到一个新的 div 中,紧跟在 h2 的父级之后。它使用 contents() 方法来包含文本节点:

var h2 = $('h2:first'),
hp = h2.parent(),
move;

$('<div class="foo"/>')
.insertAfter(hp)
.append(hp.contents().filter(function() { //use contents() to include text nodes
move = move || $(this).is(h2); //move everything beginning with the first h2
return move;
}));
.foo {
background: yellow;
border: 1px solid red;
margin-bottom: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
<span>Text here</span>
<h2>Title</h2>
<p>Text</p>
Text node here.
<h2>Title</h2>
<p>Text</p>
<h2>Title</h2>
<p>Text</p>
<h3>Another title</h3>
<h2>Title</h2>
<p>Text</p>
<h2>Title</h2>
<p>Text</p>
<h3>Another title</h3>
<h2>Title</h2>
<p>Text</p>
</div>

关于javascript - Jquery .insertBefore 忽略结束标签并自动关闭丢失的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33576599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com