我有一个包含 3 行的表格,其中包含可以填写值的输入。
现在我在最后一个 tr 中有一个链接,上面写着“+ 更多”。
如果按预期工作,“+ 更多”链接应该克隆上面的 tr 并将其附加到链接上方。
这就是我的距离:
$(document).ready(function(){
$('.appendRow').bind('click', function(){
var $table = $(this).closest('table');
var $tr = $(this).closest('tr');
var $trAbove = $(this).prev('tr');
$table.append($tr.clone());
});
});
我尝试使用 prev('tr')
来获取我所在的 TR 元素之前的 TR 元素,但它实际上不起作用。
第二个问题是它附加在 +More TR 下方,而不是其上方。
如何做到这一点?
最佳答案
$(this).prev('tr')
不起作用的原因是您的 appendRow
类位于链接,而不是行。 link 之前没有 tr
,prev
查看前一个同级元素(sibling = 在同一父元素内)以查看是否存在匹配选择器。它不会扫描,也不会向上提升层次结构。
不过你已经很接近了,请参阅评论:Updated Fiddle
$(document).ready(function(){
$('.appendRow').bind('click', function(){
// First get the current row
var $tr = $(this).closest('tr');
// Now the one above it
var $trAbove = $tr.prev('tr');
// Now insert the clone
$trAbove.clone().insertBefore($tr);
});
});
注意 insertBefore
的使用,这会将克隆插入到当前行之前。
关于javascript - 克隆上一个 tr 行并将其附加到当前表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19830734/