如何按行和列索引设置单元格的值

How to set value of a cell by row and column index?

本文关键字:单元格 设置 索引 何按行      更新时间:2023-09-26

我有这个到目前为止,但它不会改变单元格值:

function setCellValue(tableId, rowId, colNum, newValue)
{
    $('#'+tableId).find('tr#'+rowId).find('td:eq(colNum)').html(newValue);
};

通过连接索引创建选择器( :eq() 索引从0 开始)。虽然您需要对行选择器进行相同的操作,因为rowIdtr的索引,而不是id

function setCellValue(tableId, rowId, colNum, newValue)
{
    $('#'+tableId).find('tr:eq(' + (rowId - 1) + ')').find('td:eq(' + (colNum - 1) + ')').html(newValue);
};

或者使用 :nth-child() 伪类选择器

function setCellValue(tableId, rowId, colNum, newValue)
{
    $('#'+tableId).find('tr:nth-child(' + rowId + ')').find('td:nth-child(' + colNum + ')').html(newValue);
};

或通过避免 find() 方法使用单个选择器。

function setCellValue(tableId, rowId, colNum, newValue)
{
    $('#' + tableId + ' tr:nth-child(' + rowId + ') td:nth-child(' + colNum + ')').html(newValue);
    // or
    $('#' + tableId + ' tr:eq(' + (rowId - 1) + ') td:eq(' + (colNum - 1) + ')').html(newValue);
};