show hide divs using Next Previous button using jQuery?

前端 未结 4 1045
孤城傲影
孤城傲影 2020-12-03 04:04

for e.g i have 10

, i want to show each
on next button click & show previous
on previous button
4条回答
  •  伪装坚强ぢ
    2020-12-03 04:35

    You can do it like this:

    HTML:

    div 1
    div 2
    div 3
    div 4

    JS:

    $(document).ready(function() {
        var divs = $('.mydivs>div');
        var now = 0; // currently shown div
        divs.hide().first().show(); // hide all divs except first
        $("button[name=next]").click(function() {
            divs.eq(now).hide();
            now = (now + 1 < divs.length) ? now + 1 : 0;
            divs.eq(now).show(); // show next
        });
        $("button[name=prev]").click(function() {
            divs.eq(now).hide();
            now = (now > 0) ? now - 1 : divs.length - 1;
            divs.eq(now).show(); // show previous
        });
    });
    

    jsfiddle

提交回复
热议问题