首页 > 解决方案 > DataTables - 带有“onchange”的复选框不起作用

问题描述

我正在使用 dataTables 并希望包含一个复选框,该复选框将在更改时更新我的​​数据(选择、取消选择)。数据显示在表格中,每行都有复选框;然而:

  1. this.checked 无法识别(返回“未定义”);和
  2. 当我选择或取消选择复选框时,控制台日志中出现错误:Uncaught SyntaxError: Unexpected token ','

代码是:

{data: null,
  className: "center",
  render: function(data,type,row) {
      return ("<input type='checkbox' id=" + data.cdId + " name='update' onchange='ymActivityPatrolFunction(" + data.cdId + ", " + this.checked + ")' style='zoom: 2.0;'>")
     },
},

这使:

标签: jquerydatatables

解决方案


您只能this在函数内部传递,然后获取其他值,您可以使用它attr("id")来获取cdId值并checked获取检查值,即:true/false。

演示代码

var data = [{
    "cdId": "1gh",
    "name": "Tiger Nixon",
  },
  {
    "cdId": "2htf",
    "name": "Garrett Winters"
  },

];


var table = $('#example').DataTable({
  data: data,
  columns: [{
      targets: 0,
      data: "cdId",
      render: function(data, type, row) {
        //use only `this` and change data to `data.cdId` this is for dmo only..
        return ("<input type='checkbox' id=" + data + " name='update' onchange='ymActivityPatrolFunction(this)' style='zoom: 2.0;'>")
      },
      className: "center"
    },
    {
      "data": "name"
    }
  ]
});

function ymActivityPatrolFunction(checkeds) {
  //get id..and check if checked
  console.log($(checkeds).attr("id"), checkeds.checked)

}
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.16/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.16/datatables.min.js"></script>
<table id="example" class="table table-striped table-bordered" width="100%">
  <thead>
    <tr>
      <th>Checkbox</th>
      <th>Name</th>

    </tr>
  </thead>

  <tfoot>
    <tr>
      <th>Checkbox</th>
      <th>Name</th>

    </tr>
  </tfoot>

</table>


推荐阅读