2009-12-08 82 views
2

A similar question was asked before,但是我正在寻找使用下面只有HTML(即没有类或ID属性。)一个jQuery解决方案:如何选择两个相同标签之间的所有内容?

<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(); 

这应该:

  • 选择所有指定的元素之后的兄弟元素,而是指定元素的下一次出现之前。
  • 如果没有结束元素,则选择它下面的所有元素。
+0

你想对这些元素做什么? – Gumbo 2009-12-08 20:06:41

回答

0

这个怎么样?

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); 
6

的上一个选择应该是能够做到这一点:http://docs.jquery.com/Selectors/siblings#prevsiblings

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

你仍然需要某种形式的ID或属性来选择只是一个单一的h2元素。

+1

+1但是用'$(“h2〜*:not(h2)”)'代替。 – Gumbo 2009-12-08 19:54:42

+0

是的,我将它添加到我的答案中。谢谢! – markmywords 2009-12-08 20:02:08

+0

做得很好,markmywords。 – micahwittman 2009-12-08 20:14:11

0

为了证明,在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. 
    } 
}); 

请注意,我假设的#container在你的榜样DIV未显示。如果没有容器使用$(body).children()。

+0

并不像我一直在找的那么简单,而是很有效!谢谢。 – 2009-12-09 07:37:00

+0

没问题,你说得对。我提出了接受的答案 - 这是当之无愧的。 – micahwittman 2009-12-09 08:11:28

0

你可以做这样的事情:

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 
}); 
相关问题