我正在创建一个常见问题页面,通过单击问题来切换答案。问题是h3,答案是几个p-elements。如下所示:
<h3>The First Question</h3>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>
<h3>The Second Question</h3>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>如何切换属于某个问题的所有p-elements?我的JS在页面上切换所有p-elements:
$(document).ready(function(){
$("p").hide();
$("h3").click(function(){
$(this).nextAll("p").toggle();
});
});我不能使用div或类)。
发布于 2009-07-03 16:02:35
做到这一点的最好方法是使用each并迭代,直到到达应该停止迭代的下一个元素。在each过程中返回false会停止迭代。使用filter允许您在迭代中检查元素的类型并做出适当的响应。
$(function() {
$("p").hide();
$("h3").click(function() {
$(this).nextAll().each( function() {
if ($(this).filter('h3').length) {
return false;
}
$(this).filter('p').toggle();
});
});
});发布于 2009-07-03 16:00:20
我会这样做:
$(function() {
$("p").hide();
$("h3").click(function() {
$(this).nextAll().each(function() {
if ($(this).is('h3')) {
return false;
}
$(this).toggle();
});
});
});从each()返回false结束链。
我还建议,如果可能的话,更好地组织您的数据来处理这种情况。例如:
<h3 class="question">Why is there no soup for me?</h3>
<div class="answer">
<p>...</p>
<p>...</p>
<p>...</p>
</div>然后这个问题就变得微不足道了:
$(function() {
$("div.answer").hide();
$("h3.question").click(function() {
$(this).next().toggle();
});
});发布于 2009-07-03 17:16:17
这里有一个有趣的解决方案,它不使用.each()
$("h3").click(function() {
var idx = $("h3,p").index(this);
var nextIdx = ($("h3,p").index($(this).nextAll("h3")));
var nextPs = (nextIdx == -1) ? $("h3,p").length - idx : nextIdx - idx;
$(this).nextAll("p:lt(" + (nextPs - 1) + ")").toggle();
});我正在按索引查找下一个P。我不确定这有多实用,但这是一个很好的练习。
https://stackoverflow.com/questions/1079938
复制相似问题