I am using jQuery. I have the following html fragment:

我正在使用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>

I need to get the content that is between every h2 element, in order to do something like this:

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

First Section text

some text
more text

Second section text

one link
ddd
eee

Third section text
This is a Paragraph

I've read this resource: http://www.tutorialspoint.com/jquery/jquery-selectors.htm

我已经阅读了这个资源:http://www.tutorialspoint.com/jquery/jquery-selectors.htm

but still cannot figure how to do what I need.

但仍然无法想象如何做我需要的。

Thanks in advance!

提前致谢!

3 个解决方案

#1


3

I'd suggest the following:

我建议如下:

$('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.

JS小提琴演示。

While the above works, for its intended use, and illustrates nextUntil() (which is definitely the method to use in this scenario), I'm unsure how I might show you how to achieve your aims, since you seem to have left your use-case/requirements rather vague.

虽然上面的工作,为了它的预期用途,并说明nextUntil()(这绝对是在这种情况下使用的方法),我不确定如何我可以告诉你如何实现你的目标,因为你似乎离开了你用例/要求相当模糊。

References:

  • append().
  • each().
  • insertAfter().
  • nextUntil().

更多相关文章

  1. 我得到一个警告坏js小提琴配置
  2. 计算机视觉相关代码片段(Python)
  3. 在混合的Bash-Python代码片段中,变量的双引号和单引号
  4. 使用片段活动创建的ADT空白活动。
  5. Android有用的代码片段
  6. 这些片段在Android编程中很有用
  7. ViewPager中的错误片段接收onContextItemSelected调用
  8. 键盘打开时,带有片段的活动不会调整大小
  9. 嵌套片段不保留其状态

随机推荐

  1. Android 强制设置横屏或竖屏 设置全屏
  2. android之ListView和SimpleAdapter的组合
  3. android各种提示Dialog 弹出框
  4. 系出名门Android(7) - 控件(View)
  5. Android集成Facebook 事件统计
  6. ActionBar的自定义样式
  7. android语音搜索结果显示页实现
  8. Android用ViewPager实现多页面的切换效果
  9. 系出名门Android(4) - 活动(Activity),
  10. listview常用的优化技巧