You need to enable JavaScript to run this app. 如何使用jQuery实现datatable分页及功能异常问题排查
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery实现datatable分页及功能异常问题排查

Datatable自定义分页功能问题修复方案

你的代码存在几个核心问题导致分页异常,以下是具体问题和修正后的代码:

存在的问题

  • 语法错误:jQuery添加类的方法为驼峰写法addClass,你代码中写的addclass(小写c)会直接抛出JS错误,导致分页激活状态设置失败,后续逻辑中断。
  • 事件重复绑定:每次切换每页显示行数时,都会重新给分页按钮绑定点击事件,多次切换后点击一次分页按钮会触发多次回调,造成行显示逻辑混乱。
  • 选择器精准度不足:$(table + ' tr:gt(0)')会包含thead中的行,如果你表格有单独的thead结构,会导致行计数错误。

修正后的完整代码

var table = '#accounttable'
// 先解绑再绑定,避免事件重复绑定
$('#maxRows').off('change').on('change', function() {
  $('.pagination').html('')
  var trnum = 0
  var maxRows = parseInt($(this).val())
  // 只统计tbody内的行,排除表头
  var totalRows = $(table + ' tbody tr').length
  $(table + ' tbody tr').each(function() {
    trnum++
    if (trnum > maxRows) {
      $(this).hide()
    } else {
      $(this).show()
    }
  })
  if (totalRows > maxRows) {
    var pagenum = Math.ceil(totalRows / maxRows)
    for (var i = 1; i <= pagenum; i++) {
      $('.pagination').append(`<li data-page="${i}">
        <span>${i}<span class="sr-only">(current)</span></span>
      </li>`).show()
    }
  }
  // 修正为正确的addClass方法
  $('.pagination li:first-child').addClass('active')
  // 先解绑再绑定,避免重复绑定
  $('.pagination li').off('click').on('click', function() {
    var pageNum = parseInt($(this).attr('data-page'))
    var trIndex = 0;

    $('.pagination li').removeClass('active')
    $(this).addClass('active')

    $(table + ' tbody tr').each(function() {
      trIndex++
      var start = maxRows * (pageNum - 1)
      var end = maxRows * pageNum
      if (trIndex > end || trIndex <= start) {
        $(this).hide()
      } else {
        $(this).show()
      }
    })
  })
})

效果展示

分页效果展示图

内容的提问来源于stack exchange,提问作者ジェン ジェン

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 00:15:03