0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

jQuery テーブルページネーション

Last updated at Posted at 2024-12-24
Page 1 of 2
var menu = {};
// JSONファイルのデータを読み込み: $.getJSONだとうまくいかないので、$.ajaxを使用
$.ajax({
    url: './json/menu.json',
    dataType: 'json',
    async: false,
    success: function (data) {
        menu = data;
    }
});

// ページング機能
var pagination = function () {
    // 初期値設定
    var page = 1; // 現在のページ(何ページ目か)
    var step = 5; // ステップ数(1ページに表示する項目数)

    // 現在のページ/全ページ を表示
    var count = function (page, step) {
        var total = (menu.length % step === 0) ? (menu.length / step) : (Math.floor(menu.length / step) + 1);
        $('.count').text(page + "/" + total + "ページ");
    };

    // ページを表示
    var show = function (page, step) {
        // 一度テーブルを空にする
        $('.menu_list tbody').empty();
        var first = (page - 1) * step + 1;
        var last = page * step;

        for (var i = 0; i < menu.length; i++) {
            if (i < first - 1 || i > last - 1) continue;

            // テンプレートリテラルを避ける
            var row = $('<tr data-id="' + menu[i].id + '">').append(
                '<td>' + menu[i].name + '</td>',
                '<td>' + menu[i].price + '</td>'
            );
            $('.menu_list tbody').append(row);
        }
        count(page, step);
    };

    // 最初に1ページ目を表示
    show(page, step);

    // 最前ページ遷移トリガー
    $(document).on('click', '#first', function () {
        if (page <= 1) return;
        page = 1;
        show(page, step);
    });

    // 前ページ遷移トリガー
    $(document).on('click', '#prev', function () {
        if (page <= 1) return;
        page = page - 1;
        show(page, step);
    });

    // 次ページ遷移トリガー
    $(document).on('click', '#next', function () {
        if (page >= Math.ceil(menu.length / step)) return;
        page = page + 1;
        show(page, step);
    });

    // 最終ページ遷移トリガー
    $(document).on('click', '#last', function () {
        if (page >= Math.ceil(menu.length / step)) return;
        page = Math.ceil(menu.length / step);
        show(page, step);
    });
};

$(window).on('load', function () {
    pagination();
});
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?