开发者

jQuery show/hide for FAQ using the next() function

Maybe it's because it's Friday but I'm stuck on a simple problem. I'm building a FAQ page where a user clicks on a question, revealing the answer beneath it. I'm trying to get the next() function to just grab the next instance of an "answer" div but, despite not getting any JS errors, the hidden div isn't showing.

Here's the code:

.answer { display:none; }


$("a.question").click(function(){
 $(this).next(".answer").toggle();
}); 

<a href="#" class="question">Queston 1</a>
<div class="answer">Answer 1</div>

<a href="#" class="question">Queston 2</a>
<div class="answer">Answer 2</d开发者_如何学Goiv>


It works for me.

You probably have some other element between the question and the answer.

If so, change it to

$(this).nextAll(".answer:first").toggle();

Alternatively, you might be running your code in the <head> tag, before the <body> is parsed.

If so, move your <script> below the question tags, or wrap it in $(function() { ... });.


Use:

$(function(){
    $("a.question").click(function(){
     $(this).next().toggle();
     return false;
    }); 
});


That looks like it should work fine.. have you tried just $(this).next().toggle()?


Make sure to wrap your code in a document.ready, like this:

$(function() {
  $("a.question").click(function(){
    $(this).next(".answer").toggle();
  }); 
});

Without document.ready it's running the selector $("a.question") and not finding anything, because the links aren't there/ready yet, you can see this by doing alert($("a.question").length);. By putting it in document.ready it doesn't run the code to look for the elements until they are in the DOM and ready to go.

Your code itself works fine, see a demo here. You may also be interested in .slideToggle() if you want a nice effect, you can see it working here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜