使用表外的总记录更新Div

时间:2019-06-24 15:48:55

标签: javascript datatables

我正在使用数据表,并试图找出我做错了什么。当表格在表格上命中绘制事件时,我试图显示总行数。现在,使用代码,我在下面显示我没有收到任何控制台错误。应该更新编号的元素是正确的。我只是没有让它以正确的数量呈现。

("use strict");

const renderStatusCell = (data, type, full, meta) => {
    const status = {
        0: { title: "Inactive" },
        1: { title: "Active" }
    };
    if (typeof status[data] === "undefined") {
        return data;
    }
    return status[data].title;
};

var table = $('[data-table="users.index"]');

// begin first table
table.DataTable({
    // Order settings
    order: [[1, "desc"]],
    ajax: "/titles",
    columns: [
        { data: "id", title: "User ID" },
        { data: "name", title: "Name" },
        { data: "slug", title: "Slug" },
        { data: "introduced_at", title: "Date Introduced" },
        { data: "is_active", title: "Status", render: renderStatusCell },
        {
            data: "action",
            title: "Actions",
            orderable: false,
            responsivePriority: -1
        }
    ]
});

var updateTotal = function() {
    table.on("draw", function() {
        $("#kt_subheader_total").html(table.fnSettings().fnRecordsTotal());
    });
};

我希望在渲染表格时以正确的行数更新dom,但是div不会更新。

2 个答案:

答案 0 :(得分:0)

我不明白您的问题,但我认为您需要类似的东西。

table
.row($(this).parents('tr'))
.remove()
.draw();

table.ajax.reload();

答案 1 :(得分:0)

我相信您需要等到HTML加载后才能运行所有JavaScript代码。另外,如果要存储总计,则不使其成为函数而是仅存储值。

'use strict';

// this will make sure all the HTML loads before the JavaScript runs.
$(function() {
  var table = $('[data-table="users.index"]');
  var updateTotal = null; // store in a variable

  const renderStatusCell = (data, type, full, meta) => {
    const status = {
      0: { title: "Inactive" },
      1: { title: "Active" }
    };

    if (typeof status[data] === "undefined")
        return data;

    return status[data].title;
  };

  // begin first table
  table.DataTable({
    // Order settings
    order: [[1, "desc"]],
    ajax: "/titles",
    columns: [
      { data: "id", title: "User ID" },
      { data: "name", title: "Name" },
      { data: "slug", title: "Slug" },
      { data: "introduced_at", title: "Date Introduced" },
      { data: "is_active", title: "Status", render: renderStatusCell },
      {
        data: "action",
        title: "Actions",
        orderable: false,
        responsivePriority: -1
      }
    ]
  });

  table.on("draw", function() {
    updateTotal = table.fnSettings().fnRecordsTotal();
    $("#kt_subheader_total").html(table.fnSettings().fnRecordsTotal());
  });
});