如何selectjQuery中两个标签之间的所有内容
我有一个标题和无序列表文件。
我如何使用JQuery来select一个给定的标题(通过其唯一的类名),并在该标题和下一个标题之间的所有内容?
更新:
你的build议是伟大的,但不是我在找什么。 例如,在下面的代码中,我只想访问id为“heading2”的“h1”,但是不包括id为“heading3”的“h1”。
上面提供的jQuery示例将在第一个不是“h”标签的“h”标签之后进行访问。
…或者,纠正我,如果我错了:)
<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>  两种方法特别是解决这个问题非常有用: .andSelf和.andSelf 。 第一个会抓住所有的select器之后的兄弟,而后者也会在你的select器中匹配,给你一个包含它们的jQuery对象: 
 $("#heading2") .nextUntil("#heading3").andSelf() .css("background", "red"); 
这导致以下结果:

这是我用于我的项目的解决scheme:
jQueryselect器
 (function ($) { $.fn.between = function (elm0, elm1) { var index0 = $(this).index(elm0); var index1 = $(this).index(elm1); if (index0 <= index1) return this.slice(index0, index1 + 1); else return this.slice(index1, index0 + 1); } })(jQuery); 
用法
 $('body').between($('#someid'), $('#someid2')).each(function () { // Do what you want. }); 
 $('#secondSelector').prevAll('#firstSelector ~ *') 
是啊,你说得对。 这只会避免所需的select器。 也许它需要更加详细:
 $(firstSelector).nextAll().not(secondSelector).not($(secondSelector).nextAll()).text() 
也许,与
 $(selectorForFirstHeading).nextAll().not(selectorForLastHeading).text() 
 为什么我使用text() ? 因为html()将只返回第一个结果元素的内部HTML 。 
 我觉得自从jQuery 1.8和更高版本发布以来,接受的答案需要一点更新。  .andSelf()已被弃用。 代替它,我们有.addBack() 。  文档解释了你需要知道的一切。 
如果你的元素在同一层次上,像这样:
 <h1 id="heading1">...</h1> <ul>...</ul> <p>...</p> <ul>...</ul> <p>...</p> <h1 id="heading2" >...</h1> 
也就是说,您的下一个标题元素不是与第一个标题元素相同级别的元素的子元素。 你可以试试这个代码:
 // This will get all the following siblings of <h1 id="heading1"> except those that are headings themselves var elements = $('#heading1').nextAll().not("h1");