2009-12-08 44 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 
}); 
相關問題