jQuery:如何选择"从这里到下一个H2"?

Eil*_*een 30 javascript jquery dom css-selectors jquery-selectors

我正在用jQuery设置一个非常简单的FAQ页面.像这样:

<h2>What happens when you click on this question?</h2>
<p>This answer will appear!</p>
Run Code Online (Sandbox Code Playgroud)

这都是一个非常具体的div,所以我将选择标题$('#faq h2').简单吧?单击H2,然后使用this.next()以显示下一段.

(这个页面的警告是非程序员将维护它,这就是为什么我不使用类:不能保证任何新条目都有正确的类.)

所以!问题:

<h2>What happens when you click on the next question?</h2>
<p>That is an interesting conundrum.</p>
<p>Because the maintainer is kind of long-winded</p>
<p>and many answers will span a few paragraphs.</p>
Run Code Online (Sandbox Code Playgroud)

那么如何在没有添加divs和类以及诸如此类的东西的情况下,如何在我的this.next()例程中选择点击的问题和下一个问题(H2标题)之间的所有内容?

Joh*_*lum 27

我意识到这是一个老问题,但jQuery 1.4现在有nextUntil.所以这样的东西现在应该有效:

$('h2').click(function(){
    $(this).nextUntil('h2').show();
})
Run Code Online (Sandbox Code Playgroud)

  • +1用于将此有用功能添加到这样一个旧问题中. (2认同)
  • 如果你将`.show()`更改为`.toggle()`会更好,这样你就可以同时获得隐藏和显示功能.:) (2认同)

cle*_*tus 21

有趣的问题.首先让我说,我认为最好的策略是将整个答案放在一个div中然后问题变得微不足道:

<h2>Question here</h2>
<div>
<p>Answer here</p>
</div>
</h2>Next Question</h2>
...
Run Code Online (Sandbox Code Playgroud)

有:

$(function() {
  $("h2").click(function() {
    $(this).next().toggleClass("highlighted");
  });
});
Run Code Online (Sandbox Code Playgroud)

但话虽如此,没有它,它是可以解决的.

$(function() {
  $("h2").click(function() {
    $(this).nextAll().each(function() {
      if (this.tagName == 'H2') {
        return false; // stop execution
      }
      $(this).toggleClass("highlighted");
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

不是非常优雅,但它会工作.

注意:这假设问题是兄弟姐妹.如果它们不是它会变得更复杂.


Dmi*_*kov 7

使用css样式的DL列表会不会更有意义?

<dl class="faq">
    <dt>Question?</dt>
    <dd>
         <p>Answer</p>
         <p>Answer</p>
         <p>Answer</p>
    </dd>
</dl>
Run Code Online (Sandbox Code Playgroud)

然后使用以下方法轻松选择

$('+ dd', this); 
Run Code Online (Sandbox Code Playgroud)

这是当前的dt选择.

或者只是将每个答案包装在一个div中,因为它在语义上也是有意义的.但是我认为DL列表在语义上更有意义.


gra*_*bot 5

当然!只需做一个循环.

$('h2').click(function() {
    var next = $(this).next();
    while (next.length != 0 && next[0].nodeName == 'P')
    {
        next.toggle();
        next = next.next();
    }
});
Run Code Online (Sandbox Code Playgroud)

这假设你的h2之后只有p标签.如果要添加类似img的内容,可以向while循环添加更多异常.

或者如果你不关心H2标签之间的什么,你可以检查不等于H2.

$('h2').click(function() {
    var next = $(this).next();
    while (next.length != 0 && next[0].nodeName != 'H2')
    {
        next.toggle();
        next = next.next();
    }
});
Run Code Online (Sandbox Code Playgroud)

这将隐藏在点击H2之后的所有内容,直到找到下一个H2或者你在dom中达到一个级别.