jQuery показать / скрыть, чтобы пролистать таблицы - PullRequest
2 голосов
/ 25 февраля 2010

Мне нужно настроить jquery для циклического перемещения по таблицам, чтобы убедиться, что он показывает / скрывает правильную.

Основная структура HTML:

<p><a href="#" class="month-next">Next Month</a></p>

<table class="month-show"><tr><td>blurb</td></tr></table>
<table class="month-hide"><tr><td>blurb</td></tr></table>
<table class="month-hide"><tr><td>blurb</td></tr></table>
<table class="month-hide"><tr><td>blurb</td></tr></table>

и т.д.

Итак, в jQuery пока у меня есть:

$(".month-next").click(function () {
 $("table.month-show").hide();
 HERE I NEED SOME CODE TO ONLY SHOW THE NEXT TABLE IN THE HTML .show();
 return false;
});

Ответы [ 4 ]

4 голосов
/ 25 февраля 2010
$(".month-next").click(function () {
 $("table.month-show").hide().next().show();
 return false;
});

вы также можете изменить классы, чтобы следующий вызов также работал ( edit: вставленные изменения, предложенные Mark Schultheiss ):

$(".month-next").click(function () {
    $("table.month-show")
        .hide()
        .removeClass("month-show")
        .addClass("month-hide")
        .next()
        .show()
        .removeClass("month-hide")
        .addClass("month-show");
    if ($("table").hasClass('month-show').length < 1) {
        $('table').eq(0).addClass('month-show');
    }
 return false;
});
2 голосов
/ 25 февраля 2010

Это рабочий пример того, как я бы это сделал: http://jsbin.com/ogika

CSS:

.month.hide { display: none; }

HTML

<p><a href="#" class="month-next">Next Month</a></p>

<table class="month"><tr><td>a</td></tr></table>
<table class="month hide"><tr><td>b</td></tr></table>
<table class="month hide"><tr><td>c</td></tr></table>
<table class="month hide"><tr><td>d</td></tr></table>

JavaScript:

$(function () {
    $(".month-next").click(function () {
        var months = $(".month"), numMonths = months.length, curr = 0;
        return function () {
            //Hide the current table, by adding the 'hide' class
            months.eq(curr).addClass("hide"); 

            //Get the index of next table in the list
            curr = (curr + 1) % numMonths;  

            //Show the next table, by removing the 'hide' class
            months.eq(curr).removeClass("hide"); 
        }
    }());
});

В приведенном выше коде months - это список таблиц ... который в данном случае содержит 4 элемента; и numMonths - количество элементов ... т.е. 4.

«Волшебство» приведенного выше кода - это строка: curr = (curr + 1) % numMonths;

Эта строка получает индекс следующего элемента, который будет отображаться, и работает по кругу.

Давайте рассмотрим пример:

   0     1     2     3
=========================
|  a  |  b  |  c  |  d  |
=========================

Теперь, скажем, curr равно 0:

   0     1     2     3
=========================
|  a  |  b  |  c  |  d  |
=========================
   ^

//curr is currently 0
curr = (curr + 1) % numMonths; //(0 + 1) % 4
//now, curr is 1

   0     1     2     3
=========================
|  a  |  b  |  c  |  d  |
=========================
         ^

После выполнения этой строки кода curr становится 1: (0 + 1)% 4 = 1. Это означает, что следующий индекс отображаемого элемента равен 1. Следовательно, мы получаем следующий элемент и показать это, удалив класс hide: months.eq(curr).removeClass("hide");

Теперь давайте посмотрим на пример, где curr - последний элемент: 3

   0     1     2     3
=========================
|  a  |  b  |  c  |  d  |
=========================
                     ^

//curr is currently 3
curr = (curr + 1) % numMonths; //(3 + 1) % 4
//now, curr is 0

   0     1     2     3
=========================
|  a  |  b  |  c  |  d  |
=========================
   ^

Как видите, curr теперь равно 0 ... и, таким образом, цикл продолжается.

1 голос
/ 25 февраля 2010

Вы можете попробовать это:

<script type="text/javascript">
    $(function () {
        $(".month-hide").hide();
        $(".month-next").click(function () {
            $(".month-show+table").addClass("month-show").removeClass("month-hide").show();
            $(".month-show").filter(":first").removeClass("month-show").hide();
        });
    });
</script>
1 голос
/ 25 февраля 2010

Вот, пожалуйста. Это должно работать (и даже заботится о велосипеде). Возможно, вам придется внести некоторые небольшие изменения из-за другой разметки на вашей странице.

<html>
<head>
<script language="javascript" src="jquery-1.3.2.js"></script>

<script language="javascript">
$(document).ready(function(){

    $(".month-next").click(function () {
     var $monthShow = $("table.month-show");
     var $monthNext = $monthShow.next('table.month-hide');
    if($monthNext.length == 0){
        $monthNext = $('table.month-hide:first');
        }
     $monthShow.removeClass('month-show').addClass('month-hide');
     $monthNext.removeClass('month-hide').addClass('month-show');
     return false;
    });

});
</script>
<style type="text/css">
.month-show{ display:block;}
.month-hide{ display:none;}

</style>
</head>
<body>

<p><a href="#" class="month-next">Next Month</a></p>

<table class="month-show"><tr><td>blurb1</td></tr></table>
<table class="month-hide"><tr><td>blurb2</td></tr></table>
<table class="month-hide"><tr><td>blurb3</td></tr></table>
<table class="month-hide"><tr><td>blurb4</td></tr></table>

</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...