0

I have a block of code below that I am using when the next button on my quiz is clicked to go to the next question. There are 4 possible answers(input radio buttons) inside each .questionContainer div, of which there are 5 for the 5 questions.

I want to allow the user to click on a specific question number and go right to that question. The .next() line of code is working correctly to advance to the next question and possible answeres, but the line that I have commented out does not work. What am I doing wrong??? Thanks

$('.btnNext').click(function(){
    $(this).parents('.questionContainer').fadeOut(500, function(){
        $(this).next().fadeIn(500);
    //$(this).eq(1).fadeIn(500);
    });

}); 
4

2 回答 2

1

我建议使用:

$('.questionContainer').eq($(this).index()).fadeIn(500);

这假设您正在单击一个a(或其他元素),该元素的兄弟姐妹对应于.questionContainer每个应该显示的元素,类似于:

<div id="wrapper">
    <div class="questionContainer">
        <!-- question one -->
    </div>
    <div class="questionContainer">
        <!-- question two -->
    </div>
    <div class="questionContainer">
        <!-- question three -->
    </div>
    <div class="questionContainer">
        <!-- question four -->
    </div>
    <div class="questionContainer">
        <!-- question five -->
    </div>
</div>

<div id="buttons">
    <a href="#">Question 1</a>
    <a href="#">Question 2</a>
    <a href="#">Question 3</a>
    <a href="#">Question 4</a>
    <a href="#">Question 5</a>
</div>

如果您单击的元素不是同级元素,则可以将选择器传递给该index()方法以查找正确的索引。这可以是任何 CSS 类型的选择器,基于类名、元素类型、父级...等。

您的第一段代码没有而且不能工作的原因是$(this)(and this) 一次只能引用一个元素/DOM 节点,因此this(and $(this)) 总是有一个隐式索引0(是第一个,也是唯一一个元素集合中的元素)。

参考:

于 2012-04-09T17:47:31.863 回答
0

您可能还想尝试使用通配符“$”,它告诉 jQuery 匹配任何以 $ 结尾的 id;并设置问题的 div ids = "q1" 到 "q5":

  var q_nbr = 1 //create a variable in the global scope for the question number
  $(function() {
    $("#btnNext").click(
      function() {
        $("[id$=" + q_nbr + "]").fadeOut(500); // you may wish to omit this
        q_nbr++
        $("[id$=" + q_nbr + "]").fadeIn(500);
      }
    );
  });
于 2012-04-09T18:11:02.257 回答