我使用以下方法将表行从一个表克隆到另一个表:
$("button[name='addItem']").click(function(){
var clone = $(this).closest('tr').clone(true);
clone.appendTo('#items tbody');
})
我想避免多次克隆同一个项目,所以我尝试过这样的事情:
if(!$.contains("#items tbody",clone)){
clone.appendTo('#items tbody');
}
但它一直在抛出false
。
有人遇到过这个问题吗?
答案 0 :(得分:1)
将data-*
分配给克隆的行并稍后检查data
$("button[name='addItem']").click(function(){
var tr= $(this).closest('tr'); // the TR to clone
if( tr.data("isCloned") === true) return; // Already cloned!! Stop here
tr.data("isCloned", true); // Remember I'm cloned yey!
var clone = tr.clone(true); // clone it
clone.appendTo('#items tbody');
});
使用.addClass()
的另一种方式:
$("button[name='addItem']").click(function(){
var tr = $(this).closest('tr:not(".isCloned")'); // the TR to clone?
tr.addClass("isCloned"); // Remember I'm cloned yey!
var clone = tr.clone(true); // clone it
clone.appendTo('#items tbody');
});
最后一个示例可能并不明显,但如果选择器没有返回任何内容(感谢:not()
选择器),则不会克隆和附加任何内容。
答案 1 :(得分:0)
如果禁用该按钮,则无法再次添加该行。
$("button[name='addItem']").click(function(){
this.disabled = true;
var clone = $(this).closest('tr').clone(true);
//clone.find("button").remove();
clone.appendTo('#items tbody');
})
table { width:40%; height:140px; display:inline-block; border:1px solid black;}
<table id="source">
<tbody>
<tr><td><button type='button' name='addItem'>+<td>1<td>one
<tr><td><button type='button' name='addItem'>+<td>2<td>two
<tr><td><button type='button' name='addItem'>+<td>3<td>three
<tr><td><button type='button' name='addItem'>+<td>4<td>four
<tr><td><button type='button' name='addItem'>+<td>5<td>five
</table>
<table id="items"><tbody>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>