简体   繁体   English

如何克隆和 append 空元素

[英]How to clone and append empty element

I would like to append empty html rows.我想将 append 空 html 行。

My desired result is to append html rows and remove its(appended row's) contents.我想要的结果是 append html 行并删除其(附加行的)内容。

to achieve it,I apply .html('') method.为了实现它,我应用了.html('')方法。

But it didn't work well.但效果并不好。

My work is like below.我的工作如下。

How can I append rows and remove its (appended rows) contents?如何 append 行并删除其(附加行)内容?

Thanks谢谢

 $(document).ready(function() { $("table").on( "click", "tr", function() { $("table").append($(this).clone().html(' ')); }); });
 table { border-collapse:collapse;} td { border:solid black 1px; transition-duration:0.5s; padding: 5px; cursor:pointer;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody> <tr> <td>0</td> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> </tr> </tbody> </table>

Why don't you simply insert tr instead of cloning and removing its html?为什么不简单地插入tr而不是克隆和删除它的 html?

$("table").on( "click", "tr", function() {
   $(this).after("<tr />");
});

If you want to clone td as well, then you can do:如果你也想克隆td ,那么你可以这样做:

$("table").on( "click", "tr", function() {
   var row = $(this).clone().find('td').html('');
   $(this).after(row);
});

If you want to append cloned element at the end of table, then you can do:如果你想 append 在表的末尾克隆元素,那么你可以这样做:

$("table").on( "click", "tr", function() {
   var row = $(this).clone().find('td').html('');
   row.appendTo('table');
});

Or even:甚至:

$('table').append(row)

To conclude on what you were doing wrong is emptying the cloned element instead of its td html.总结你做错了什么是清空克隆的元素而不是它的td html。

 $(document).ready(function() { var table=$("table"); table.on( "click", "tr", function() { var clonedTr=$(this).clone(); clonedTr.find("td").html(""); table.append(clonedTr); }); });
 table { border-collapse:collapse;} td { border:solid black 1px; transition-duration:0.5s; padding: 5px; cursor:pointer;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody> <tr> <td>0</td> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> </tr> </tbody> </table>

This works:这有效:

 $( document ).ready(function() { $('#tableID').on( "click", "tr", function() { var elt = $(this).clone() elt.find('td').empty() $('#tableID').append(elt) }) });
 table td { border: 1px solid; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="tableID"> <tbody> <tr> <td>0</td> <td>1</td> <td>2</td> </tr> </tbody> </table>

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

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