Javascript 切换下一节

Javascript 切换下一节,javascript,jquery,html,Javascript,Jquery,Html,我有一块HTML: <form> <section> <div class="row normalTopPadding personalInfomation"> <!--Loads of HTML and Stuff--> <a id="myButton" class="reg-next-button btn btn-default">Next</a>

我有一块HTML:

<form>
    <section>
        <div class="row normalTopPadding personalInfomation">
            <!--Loads of HTML and Stuff-->
            <a id="myButton" class="reg-next-button btn btn-default">Next</a>
        </div>
    </section>

    <section>
        <div class="row normalTopPadding employerInfomation">
            <!--Loads of HTML and Stuff-->
            <a id="myButton" class="reg-next-button btn btn-default">Next</a>
        </div>
    </section>

    <section>
        <div class="row normalTopPadding accountInfomation">
            <!--Loads of HTML and Stuff-->
            <a id="myButton" class="reg-next-button btn btn-default">Next</a>
        </div>
    </section>
</form>
我试图实现的是,每次单击按钮时,隐藏已单击按钮的面板,并向下显示下一个面板,因此

<script>
$('.personalInfomation .reg-next-button, .employerInformation .reg-next-button', .accountInformation .reg-next-button').click(function (e) {
    // Get the section that this button lives in
    var form = $(this).closest("section");

    //validation and other functions commented out for ease of reading

    // Hide this section...
    section.toggle();
    // And show the next section
    section.next().toggle();

});
</script>
虽然这会隐藏已单击按钮的区域,但不会显示下一个区域

有人能指出我的错误吗

谢谢,
C

您可以先尝试隐藏所有部分,然后单击a,找到要显示的下一行

请参见下面的演示:

$'.row'.not':first'.css'display','none'; $'.行>a'.单击函数{ $this.parents'.row'.toggle; $this.parents'section'。next'section'。find'。row'。切换; } 下一个1 下一个2 下一个3
您可以检查下一节是否可用,然后隐藏当前节

注意:jquery选择器中有额外的单引号,我已经删除了它。另外,您已经声明了变量表单,但使用了section,所以将表单重命名为section

$('.personalInfomation .reg-next-button, .employerInformation .reg-next-button, .accountInformation .reg-next-button').click(function (e) {
    // Get the section that this button lives in
    var section = $(this).closest("section");

    //validation and other functions commented out for ease of reading

    // Hide this section...
    var $next = section.next();
    if($next.length>0) {  // check condition first and then hide current section and show next
       section.toggle();
      // And show the next section
      $next.toggle();
   }
});
不用将每个部分放入按钮点击处理程序中,您可以对其进行概括并改进代码,以便在添加新部分时不需要更改脚本

注意-不要对多个html元素使用与按钮相同的id

$function{ $'section.row.normalTopPadding.reg下一步按钮'。单击“单击”,函数e{ var section=$this.closestsection; var$next=section.next; 如果$next.length>0{//首先检查条件,然后隐藏当前节并显示下一个 节。添加类“隐藏”; $next.removeClass'hide'; } }; }; .隐藏{ 显示:无; } 这是第一节 下一个 这是第2节 下一个 这是第3节 下一个
不能有多个具有相同id的元素。如果发现有问题,请尝试更改var form=$this.closestsection;to var section=$this.closestsection;最后一节还有一个“下一步”按钮。。。这应该是…更改var form=$this.closestsection;to var section=$this.closestsection;不隐藏当前节或显示下一节。正式注意到重复ID的复制和粘贴是为了方便。您好,谢谢,但这仍然是,但它没有找到下一个显示的部分,因此没有隐藏当前缺少的部分,您已经定义了表单变量并使用了部分变量。我在回答中已经改正了。此外,还提供了其他带有css类隐藏的干净解决方案