jQuery:如何选择“从这里直到下一个H2”? [英] jQuery: How to select "from here until the next H2"?
问题描述
我使用jQuery设置了一个非常简单的FAQ页面。像这样:
I'm setting up a very straightforward FAQ page with jQuery. Like so:
<h2>What happens when you click on this question?</h2>
<p>This answer will appear!</p>
这是一个非常特定的div,所以我将选择 $('#faq h2')
。简单,对吧?点击H2,使用 this.next()
显示下一段。
This is all inside a very specific div, so I'll be selecting the header with $('#faq h2')
. Simple, right? Click on the H2, and use this.next()
to make the next paragraph show up.
注意这个页面是非程序员将维护它,这就是为什么我不使用类:不能保证任何新的条目将有正确的类中。)
(The caveat with this page is that a non-programmer will be maintaining it, which is why I'm not using classes: there's no guarantee that any new entries would have the right classes in them.)
那么!问题:
<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>
那么如何在 div
和类和什么,我可以让我的 this.next()
例程选择问题 - 被点击和下一个问题(H2标题)之间的一切?
So how, without adding in div
s and classes and whatnot, can I have my this.next()
routine select everything between the question-that-was-clicked-on and the next question (H2 header)?
推荐答案
有趣的问题。首先让我说,我认为最好的策略是把整个答案放在一个div,然后问题变得微不足道的解决:
Interesting problem. First let me say that I think the best strategy is to enclose the whole answer in a div and then the problem becomes trivial to solve:
<h2>Question here</h2>
<div>
<p>Answer here</p>
</div>
</h2>Next Question</h2>
...
包含:
$(function() {
$("h2").click(function() {
$(this).next().toggleClass("highlighted");
});
});
但是话说回来,没有这个可以解决。
But that being said, it is solvable without that.
$(function() {
$("h2").click(function() {
$(this).nextAll().each(function() {
if (this.tagName == 'H2') {
return false; // stop execution
}
$(this).toggleClass("highlighted");
});
});
});
不是非常优雅,但它会工作。
Not supremely elegant but it'll work.
注意:这假设问题是兄弟姐妹。如果他们不是,它变得更加复杂。
Note: This assumes the questions are siblings. If they are not it gets much more complicated.
这篇关于jQuery:如何选择“从这里直到下一个H2”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!