My HTML consists of lines of text(questions) and a button beside each to show/hide answers. It is something like this.
<div id="test">
<ul>
<li>ques 1 <button>view/hide answer</button> </li>
<div id="ans1">
Answer 1
</div>
<li>ques 2 <button>view/hide answer</button></li>
<div id="ans2">
Answer 2
</div>
.
.
.
</ul>
</div>
What I'm trying to achieve is a single function which can take the id of the clicked button or say the class of button and show/hide the div after it. Using jQuery I can provide different ids to each and write code for the same but that'll be a foolish thing to do as I have a lot of questions to show. I hope I'm able to explain myself well. There may be a very easy way to do it but unfortunately I just can't get to 开发者_StackOverflow社区it. Hope someone out there will help me out.
There's a couple of jQuery methods that will help you out:
next
- Probably your best bet.nextAll
To show the next element after a button
element, do this:
$('button').click(function() {
$(this).next().slideToggle();
});
If you change your layout and the the div
happens not to be the very next element, then you'll need to use nextAll
with an appropriate selector, which looks at all subsequent sibling elements, not just the very next one.
This does exactly what you want:
$("button").click(function() {
$(this).parent().next().toggle();
});
It hides the first element right after the parent element of the button.
http://jsfiddle.net/nayish/hxRuG/2/
Try this.
$(function(){
$("#test button").click(function(){
//next() will get the next sibling of the button clicked.
$(this).parent().next().slideToggle();
});
});
精彩评论