我有一个带有输入字段的数据表。当用户输入到一个字段时,我需要找到他们输入的行号。我之前问过一个问题,并得到了一个很好的答案,但是如果数据表是响应式的,并且字段在子弹出窗口中,答案就不再起作用了。
这是我的代码:
function drawInput(data, type, row, meta) {
return '<input id="r' + meta.row + 'c' + meta.col + '" val="' + data + '"></input>';
}
var data = [{
c1: 'r1c1',
c2: 'r1c2',
c3: 'r1c3'
}, {
c1: 'r2c1',
c2: 'r2c2',
c3: 'r2c3'
}];
$(function() {
var table = $('table').dataTable({
info: false,
searching: false,
ordering: false,
paging: false,
columns: [{
defaultContent: '<span></span>'
},
{
data: 'c1',
name: 'c1',
defaultContent: '<input></input>',
render: drawInput
},
{
data: 'c2',
name: 'c2',
defaultContent: '<input></input>',
render: drawInput
},
{
data: 'c3',
name: 'c3',
defaultContent: '<input></input>',
render: drawInput
}
]
});
table.api().rows.add(data);
table.api().draw();
$('body').on('change', 'table :input', function(e) {
// 找到包含输入字段的行
//console.log(this);
var row = table.api().row($(this).closest('td'));
// 显示行索引 - 结果为undefined!为什么?
console.log(row.index());
});
});
<link href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<div style='width:150px;'>
<table width="100%" class="responsive">
<thead>
<tr>
<th></th>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
</table>
</div>
如果你在一个足够大的窗口中运行这个代码,它就可以正常工作。但是如果你缩小窗口,使得右边的列响应式地下降到子行中,找到行索引的代码就不再起作用了。
如何正确找到子单元格的行?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
当
.row($(this).closest("td")).index()未定义时,使用table.api().row(this).index()。奇怪的是,
table.api().row(this)只适用于展开的行,而不是原始行,所以需要继续使用.closest("td")来获取原始行。具体来说,
table.api().row(...)将返回一个jQuery对象,因此要检查是否返回了任何行,请检查.length === 0。给出:
let row = table.api().row($(this).closest("td")) if (row.length === 0) row = table.api().row(this);然后
.index()将给出预期的行索引。更新的代码片段: