前端表格使用的是 bootstrap-table
前端相关代码
<table id="table"></table>
<script>
$table.on("click-cell.bs.table", handleCellClick)
function handleCellClick(e, field, value, row, $element) {
if (field === "xxx" || field === "xxx") {
....
}else if (field === ""){ // 我要能上下键切换编辑的单元格
$element.attr('contenteditable', true).focus()
bindEditHandlers($element, field, value, $element.parent().data('index'));
}
}
function bindEditHandlers($cell, field, value, rowIndex){
$cell.unbind('blur').bind('blur', function () {
let tdValue = $cell.text()
// console.log("旧数据:", value, " 新数据:", tdValue)
if(value == tdValue){
return;
}else{
let row = $table.bootstrapTable('getData')[rowIndex];
let index = $cell.parent().data('index')
console.log("rowIndex", rowIndex, "index", index)
saveData(row.id, field, tdValue, row, $cell, index) // 自己的后端交互方法
}
})
$cell.unbind('keydown').bind('keydown', function (e) {
if(e.which === 40){ // 键盘下键
e.preventDefault(); // 阻止默认行为
let nextRow = $cell.closest('tr').next();
if(nextRow.length){
let nextCell = nextRow.find('td').eq($cell.index());
if (nextCell.length){
nextCell.attr('contenteditable', true);
$cell.removeAttr('contenteditable');
nextCell.focus();
bindEditHandlers(nextCell, field, nextCell.text(), nextRow.data('index'));
}else {
console.log("没找到 nextCell")
}
}else {
console.log("没找到 nextRow")
}
}else if (e.which === 38){ // 键盘上键
e.preventDefault(); // 阻止默认行为
let previousRow = $cell.closest('tr').prev();
if (previousRow.length){
let previousCell = previousRow.find('td').eq($cell.index());
if (previousCell.length){
previousCell.attr('contenteditable', true);
$cell.removeAttr('contenteditable');
previousCell.focus();
bindEditHandlers(previousCell, field, previousCell.text(), previousRow.data('index'));
}else {
console.log("没找到 previousCell")
}
}else {
console.log("没找到 previousRow")
}
}else if (e.which === 13){ // 回车
e.preventDefault(); // 阻止默认行为
$(this).blur();
}
})
}