You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法获取jQuery DataTable中输入字段所在行?

问题1:jQuery DataTable无法获取输入框所在行

错误原因及修正

  1. row()方法参数错误:table.api().row(this)中的this指向input元素,但DataTables的row()方法需要传入**行元素(<tr>)**或相对于表格的节点。需先通过closest('tr')找到input所在的父行,再传入row()方法。
  2. input属性错误:drawInput函数里的val="' + data + '"不符合HTML规范,输入框的初始值属性应为value,这个错误会导致输入框初始显示为空,需修正。

修正后的代码

修改render函数和事件处理逻辑:

// 修正render函数的input属性
function drawInput(data, type, row, meta) {
    return '<input id="r' + meta.row + 'c' + meta.col + '" value="' + data + '"></input>';
}

// 修正事件处理中的行获取逻辑
$('body').on('change', 'table :input', function(e) {
    var $row = $(this).closest('tr'); // 获取input所在的tr元素
    var row = table.api().row($row);
    console.log(row.index()); // 现在能正确输出行索引
});

完整可运行代码:

<html>
<head>
<link href="//datatables.net/download/build/nightly/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script>
<script>
function drawInput(data, type, row, meta) {
    return '<input id="r' + meta.row + 'c' + meta.col + '" value="' + data + '"></input>';
}
var data = [ { c1: 'r1c1', c2: 'r1c2' }, { c1: 'r2c1', c2: 'r2c2' }];
$(function() {
    var table = $('table').dataTable({
        info: false,
        searching: false,
        ordering: false,
        paging: false,
        columns: [
            {
                data: 'c1',
                name: 'c1',
                heading: 'Col 1',
                defaultContent: '<input></input>',
                render: drawInput
            },
            {
                data: 'c2',
                name: 'c2',
                heading: 'Col 2',
                defaultContent: '<input></input>',
                render: drawInput
            }
        ]
    });
    table.api().rows.add(data);
    table.api().draw();
    $('body').on('change', 'table :input', function(e) {
        var $row = $(this).closest('tr');
        var row = table.api().row($row);
        console.log(row.index());
    });
});
</script>
</head>
<body>
 <table width="100%">
  <thead>
   <tr>
    <th>Col 1</th>
    <th>Col 2</th>
   </tr>
  </thead>
  <tbody>
 </table>
</body>
</html>
问题2:Stack Overflow添加可执行代码片段的方法

在Stack Overflow的提问/回答编辑器中按以下步骤操作:

  • 点击工具栏中的**<>**按钮(插入代码片段),弹出代码编辑窗口。
  • 在窗口中分别填写HTML、CSS、JavaScript代码;如果是完整HTML页面,直接把所有内容放到HTML标签页即可。
  • 完成后点击"Insert",发布内容后,代码块上方会出现"Run code snippet"按钮,点击即可运行代码。

也可以直接粘贴完整HTML代码,选中代码块后在语言选择器中选"HTML",编辑器会自动识别为可执行片段,发布后同样会显示运行按钮。

内容的提问来源于stack exchange,提问作者Nikki Locke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:22:45