简体   繁体   English

避免克隆重复

[英]Avoid clone duplication

I'm cloning table rows from one table to another using this:我正在使用这个将表行从一个表克隆到另一个表:

$("button[name='addItem']").click(function(){
    var clone = $(this).closest('tr').clone(true);
    clone.appendTo('#items tbody');
  })

I'd like to avoid cloning the same item more than once, so I tried something like this:我想避免多次克隆同一个项目,所以我尝试了这样的事情:

if(!$.contains("#items tbody",clone)){
  clone.appendTo('#items tbody');
}

but it keeps throwing false .但它不断抛出false

Has someone faced this problem?有人遇到过这个问题吗?

Assign data-* to a cloned row and check for that data laterdata-*分配给克隆的行并稍后检查该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');
});

Another way using .addClass() :另一种使用.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');
});

the last example might not be obvious but if the selector returns nothing (thanks to the :not() selector) than nothing will be cloned and appended.最后一个例子可能不明显,但如果选择器不返回任何内容(感谢:not()选择器),则不会克隆和附加任何内容。

If you disable the button you cannot add the row again.如果禁用该按钮,则无法再次添加该行。

 $("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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM