我有一种情况,需要在点击表中的行后添加行
为此,我知道这个
$('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);
});