代码之家  ›  专栏  ›  技术社区  ›  Beau Smith

如何选择两个相同标记之间的所有内容?

  •  2
  • Beau Smith  · 技术社区  · 16 年前

    A similar question was asked before ,但我正在寻找只使用以下html的jQuery解决方案(即不使用类或id属性):

    <h2>Foo</h2>
    <p>asdf</p>
    <ul><li>asdf</li></ul>
    <p>asdf</p>
    <h2>Bar</h2>
    <p>asdf</p>
    <p>asdf</p>
    <h2>Baz</h2>
    <p>asdf</p>
    <p>asdf</p>
    

    我想使用一些jQuery,比如:

    $('h2').afterButBeforeNext('h2').doSomething();
    

    这应:

    • 选择指定元素之后但在指定元素下一次出现之前的所有同级元素。
    • 如果没有结束元素,则选择它下面的所有元素。
    5 回复  |  直到 9 年前
        1
  •  6
  •   markmywords    16 年前

    prev选择器应能够执行以下操作: http://docs.jquery.com/Selectors/siblings#prevsiblings

    $("h2 ~ *:not(h2)").doSomething();
    

    您仍然需要某种id或属性来选择单个h2元素。

        2
  •  2
  •   Beau Smith    16 年前

    使用核心jQuery函数的最简单解决方案:

    $('h2').nextUntil('h2').doSomething();
    

    Jonathan Snook 向我介绍了解决此问题的jQuery 1.4函数:

    灵感来自:

        3
  •  0
  •   Skawful    16 年前

    这个怎么样?

    function selectBetween(node1,node2,parent)
    {
        var p = $(parent);
        var n1 = p.find(node1);
        var n2 = p.find(node2);
        var results = [];
        var start = false;
        var end = false;
        p.children().each(function()
        {
            if(!start && !end)
            {
                if($(this) === n1)
                {
                    start = true;
                }
                results.push(this);
                if($(this) === n2)
                {
                    end = true;
                    return;
                }
            }
        });
        return results;
    }
    var between = selectBetween($(parent).find('h2:first'), $(parent).find('h2:last'), parent);
    
        4
  •  0
  •   Gumbo    16 年前

    var name = "h2";
    $(name).each(function() {
        var siblings = [], sibling=this.nextSibling;
        while (sibling && sibling.nodeName.toLowerCase() != name) {
            siblings.push(sibling);
            sibling = sibling.nextSibling;
        }
        // siblings now contains an array of sibling elements that are not h2
    });
    
        5
  •  0
  •   micahwittman    16 年前

    为了演示,h2标签内容变为红色,p、ul标签内容变为绿色:

    $('#container').children().each(function(){
        if(this.nodeName == 'H2'){
            $(this).css('color','red');
            $(this).nextAll().each(function(){
                if(this.nodeName != 'H2'){
                    $(this).css('color','green');
                }
            });        
            return false; //exit here to only process the nodes between the first H2 and second H2 found.
        }
    });