简体   繁体   English

如何使用按钮在数组中的多个 div 之间切换?

[英]How to toggle between multiple divs in an array using a button?

The idea of the program is that when you click on the continue button it shows the next div in the array and hides all the others (if you're familiar with brilliant.org, it's the same as the "continue" button when you're taking a course).该程序的想法是,当您单击“继续”按钮时,它会显示数组中的下一个 div 并隐藏所有其他 div(如果您熟悉 brill.org,它与“继续”按钮相同)重新参加课程)。 However, my code doesn't work.但是,我的代码不起作用。 Thanks for the help谢谢您的帮助

HTML: HTML:

<a id="button" role="button" href="#"><h1>Continue</h1></a>
<div id="page1">text1</div>
<div id="page2">text2</div>
<div id="page3">text3</div>

JS: JS:

$("#page1").show();
$("#page2").hide();
$("#page3").hide();

var texts = [page1,page2,page3];
var arrayLength = texts.length;

$(document).on ("click","#button", function () {
        var i;
        for (i = 0; i < arrayLength; i++) {
            console.log(texts[i]);
            var text = texts[i];
            text.show();
            texts.hide();
        }
});

You can use :visible selector in order to get current one.您可以使用:visible选择器来获取当前选择器。

After with .next() you can get the next element, and if such element is one after the last one you can go back to the first ele.使用.next()之后,您可以获得下一个元素,如果该元素在最后一个元素之后,您可以返回到第一个元素。

Now you can show the next and hide the previous one.现在您可以显示下一个并隐藏上一个。

 $("#page1").show(); $("#page2").hide(); $("#page3").hide(); var texts = [page1,page2,page3]; var arrayLength = texts.length; $(document).on ("click","#button", function () { var visibleEle = $('[id^=page]:visible'); var nextEle = visibleEle.next('[id^=page]'); if (nextEle.length == 0) { nextEle = $('[id^=page]:first'); } visibleEle.hide(); nextEle.show(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a id="button" role="button" href="#"><h1>Continue</h1></a> <div id="page1">text1</div> <div id="page2">text2</div> <div id="page3">text3</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM