jquery Simple SlideToggle in sections
I am creating a simple page with questions and answers. This is how it looks:
SECTION > Question > Answer
And this keeps on repeating with different sections, Each section has multiple questions and each question has an answer. By default everything is set to display:none. Now when someone clicks on any of the section, the related set of questions should showup, and when someone clicks on the question, it;s answer should sh开发者_开发技巧ow up.
Only one section should be open at a time.
I kind of figured it would require parent(), child(), each() functions but I don't know how and where to use them :(
I have previously used javascript and used to do it via ID basis, but since I'm using jQuery, I thought I'd rewrite the page using classes as .section, .question and .answer
Here is a the simple fiddle page where I have created li elements : http://jsfiddle.net/DKMJH/2/
Your HTML is invalid, <li>
elements don't nest like that so the browser will probably try to fix it up and what sort of selector you want for the next question or answer depends on how the browser decides to mangle your HTML. You probably want this HTML:
<ul>
<li class="section">Section One</li>
<li class="question">This is a question</li>
<li class="answer">This is an answer</li>
<li class="section">Section Two</li>
<li class="question">This is another question</li>
<li class="answer">This is another answer</li>
</ul>
Now that we have valid HTML, we'll know what the final structure really is and you can use next
to find the appropriate single element to open:
$('.section').click(function() {
$(this).next('.question').slideToggle(500);
});
$('.question').click(function() {
$(this).next('.answer').slideToggle(500);
});
You also spelled cursor
wrong in your CSS but that won't have any effect on your jQuery.
Fix fiddle: http://jsfiddle.net/ambiguous/jcnMa/
ryudice was in first and got to the heart of the matter, I just needed more space than a comment to deal with the broken HTML issue. Using next
only works because the browser is restructuring your HTML into a single unordered list.
If you only want one question open at a time, then close the other ones:
$('.section').click(function() {
var $others = $('.question:visible').not(this);
$others.next('.answer').hide();
$others.slideToggle(500);
$(this).next('.question').slideToggle(500);
});
Demo: http://jsfiddle.net/ambiguous/jcnMa/1/
Here it is:
$('.question, .answer').css("display","none");
$('.section').click(function (){
$(this).next('.question').slideToggle(500);
});
$('.question').click(function (){
$(this).next('.answer').slideToggle(500);
});
I think this neater for what you want:-
$('.question, .answer').css("display", "none");
$('.section').click(function() {
$(this).nextUntil('.section', '.question, .answer:visible').slideToggle(500);
});
$('.question').click(function() {
$(this).next('.answer').slideToggle(500);
});
精彩评论