You need to enable JavaScript to run this app. Datatables报错Cannot set property '_DT_CellIndex' of undefined 无法正常运行咨询
优惠活动
大模型
产品
解决方案
定价
更多

Datatables报错Cannot set property '_DT_CellIndex' of undefined 无法正常运行咨询

报错根因

触发Cannot set property '_DT_CellIndex' of undefined报错的核心原因是生成的表格DOM结构不符合HTML规范,Datatables初始化遍历单元格时,会遇到未定义的节点对象,无法正常挂载内部索引属性。
具体结构错误点:

  • 原本全表格仅需定义1次的<tbody>标签,被错误写入while循环内部,每查询出一条数据就生成一个独立的tbody节点
  • 每一行数据对应的<tr>标签仅写了开标签,没有配套的</tr>闭合标记
  • </tbody>闭合标签同样被放在循环范围内,最终输出的是零散破碎的标签片段,没有形成标准的「table > thead > tbody > tr > td」嵌套层级
  • 附带代码逻辑问题:代码中两次为$query变量赋值,第一行SQL属于完全冗余的无效代码;SQL语句直接拼接会话变量,存在SQL注入风险
修复步骤
  1. 将<tbody>开标签、</tbody>闭标签移出while循环范围,整个表格仅保留唯一的tbody节点
  2. 给每一条循环生成的<tr>标签补上闭合标记
  3. 清理冗余的无效SQL赋值代码

修复后的核心代码示例:

<table class="table table-bordered table-striped table-fixed text-center" id="myTable">
  <thead>
    <tr>
      <th>No</th>
      <th>ID</th>
      <th>Nama</th>
      <th>Golongan</th>
      <th>Nilai Output</th>
      <th>Penilaian Atasan</th>
      <th>Nilai Learning</th>
      <th>Nilai Kedisiplinan</th>
      <th>Nilai 5R</th>
      <th>Hasil</th>
      <th>Tanggal</th>
    </tr>
  </thead>
  <!-- 循环外定义唯一的tbody -->
  <tbody>
    <?php
    $no = 0;
    // 清理冗余的第一次查询赋值,仅保留有效SQL
    $query = "SELECT user.id,user.nama,golongan,nilai_output,nilai_atasan,nilai_learning,nilai_kedisiplinan,nilai_5r,overall,tanggal 
              FROM tkaryawan 
              JOIN user ON user.id=tkaryawan.id 
              where user.id= ? 
              ORDER BY tanggal DESC";
    // 改用预编译绑定参数替代直接拼接,规避注入风险
    $stmt = $koneksi->prepare($query);
    $stmt->bind_param("i", $_SESSION['id']);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if(!$result){
      die ("Query Error: ".mysqli_errno($koneksi). " - ".mysqli_error($koneksi));
    }
    while($data = mysqli_fetch_assoc($result))
    {
      $no++;
    ?>
      <!-- 循环内仅生成tr行,带完整闭合标记 -->
      <tr>
        <td><?php echo $no;?></td>
        <td><?php echo $data['id'];?></td>
        <td class="text-capitalize"><?php echo $data['nama'];?></td>
        <td><?php echo $data['golongan'];?></td>
        <td><?php echo $data['nilai_output'];?></td>
        <td><?php echo $data['nilai_atasan'];?></td>
        <td><?php echo $data['nilai_learning'];?></td>
        <td><?php echo $data['nilai_kedisiplinan'];?></td>
        <td><?php echo $data['nilai_5r'];?></td>
        <td class="font-weight-bold text-danger"><?php echo $data['overall'];?></td>
        <td class="text-secondary"><?php echo $data['tanggal'];?></td>
      </tr>
    <?php
    }
    mysqli_free_result($result);
    mysqli_close($koneksi);
    ?>
  </tbody>
</table>

注:修复DOM结构后再初始化Datatables,即可正常加载运行,不会再触发单元格索引相关的报错。

内容的提问来源于stack exchange,提问作者Lee wayy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.27 20:15:02