如何为表tr:nth子级(rowNumber)提供动态值



我有一种情况,需要在点击表中的行后添加行

为此,我知道这个

$('table tr:nth-child(2)').after(tr); // which is working but its static.

我的要求是用下面的函数获取点击行的行号

$('#data-grid-table-tree').find('tr').click(function () {
    rowNumber = ($(this).index() + 1)
});

现在我使用$('table tr:nth-child(rowNumber)').after(tr);,它抛出错误

未捕获错误:语法错误,无法识别的表达式::第n个子

为什么?如何将动态值用于nth:child。

由于rowNumber是可变的,您需要在选择器中使用+

$('table tr:nth-child(' + rowNumber + ')').after(tr);

您也可以按照使用eq

$('table tr').eq(rowNumber).after(tr);

由于eq的索引从零开始,因此不需要将1添加到索引中。

$('#data-grid-table-tree tr').click(function () {
    rowNumber = $(this).index(); // Removed `+ 1` from here
});

编辑:

您也可以使用$(this)来引用单击的元素,并在其上使用after

$('#data-grid-table-tree tr').click(function () {
    // Code here
    $(this).after(tr);
});

您在tr上绑定了点击事件,为什么不利用它来为您带来优势呢。您想将新的tr放在它的正后方。因此,与其使用它的索引,不如将它直接插入到单击的元素之后。

$('#data-grid-table-tree').on('click', 'tr', function() {
    $(this).after(tr);
});

最新更新