gpt4 book ai didi

javascript - 如何选择两个h2之间的所有元素

转载 作者:行者123 更新时间:2023-11-30 08:50:20 24 4
gpt4 key购买 nike

我正在使用 jQuery。我有以下 html 片段:

   <h1>Main Title</h1>
<h2>One header</h2>
<p>some text</p>
<p>more text</p>
<ul><li>a list</li></ul>
<h2>Another header</h2>
<a href="######">one link</a>
<h3>ddd</h3>
<p>eee</p>

<h2>Header 3<h2>
<p>This is a Paragraph</p>

我需要获取每个 h2 元素之间的内容,以便执行如下操作:

First Section text

some text
more text

Second section text

one link
ddd
eee

Third section text
This is a Paragraph

我已阅读此资源: http://www.tutorialspoint.com/jquery/jquery-selectors.htm

但仍然不知道如何做我需要的。

提前致谢!

最佳答案

我建议如下:

$('h2').each(function(){
var self = $(this),
// gets everything between the $(this) and the next 'h2' element:
contents = self.nextUntil('h2'),
/* creates a new div with which to wrap,
and inserts after the current $(this): */
newWrap = $('<div />').insertAfter(self);
// appends the contents to the new div element:
newWrap.append(contents);
});

JS Fiddle demo .

虽然上面的方法对于它的预期用途有效,并说明了 nextUntil()(这绝对是在这种情况下使用的方法),但我不确定如何向您展示如何实现你的目标,因为你似乎已经离开了你的用例/需求相当模糊。

引用资料:

关于javascript - 如何选择两个h2之间的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18453710/

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