如何选择jQuery中两个标签之间的所有内容

如何选择jQuery中两个标签之间的所有内容

本文介绍了如何选择jQuery中两个标签之间的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含标题和无序列表的文档。

I have a document with headings and unordered lists.

如何使用JQuery选择给定的标题(通过其唯一的类名)标题和下一个标题?

How can I use JQuery to select a given heading (by its unique class name) AND all content between that heading and the next heading?

您的建议非常棒, m寻找。在下面的代码中,例如,我想只访问h1,id为heading2,一切到达,但不包括h1,ID为heading3。

Your suggestions are great, but aren't what I'm looking for. In the below code, for example, I would like to access only the "h1" with id of "heading2" and everything up to, but not including the "h1" with id of "heading3".

上面提供的jQuery示例将在第一个不是h标记的h标记后访问。

The jQuery examples provided above will access everyting after the first "h" tag that is not an "h" tag.

...或者,如果我错了,请纠正我)

... or, correct me if I'm wrong :)

    <h1 id="heading1">...</h1>
        <ul>...</ul>
        <p>...</p>
        <ul>...</ul>
        <p>...</p>
    <h1 id="heading2" >...</h1>
        <ul>...</ul>
        <p>...</p>
        <ul>...</ul>
        <p>...</p>
    <h1 id="heading3" >...</h1>
        <ul>...</ul>
        <p>...</p>
        <ul>...</ul>
        <p>...</p>


推荐答案

:和。第一个将抓住所有的兄弟姐妹跟随你的选择器,并且后者将在选择器匹配的任何东西,将给你一个jQuery对象,包括所有:

Two methods in particular would be very useful solving this problem: .nextUntil, and .andSelf. The first will grab all of the siblings following your selector, and the latter will lump in whatever is matched by your selector as well, giving you one jQuery object that includes them all:

$("#heading2")
    .nextUntil("#heading3").andSelf()
        .css("background", "red");

这会导致以下结果:

这篇关于如何选择jQuery中两个标签之间的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 07:26