简体   繁体   中英

How to clone and append empty element

I would like to append empty html rows.

My desired result is to append html rows and remove its(appended row's) contents.

to achieve it,I apply .html('') method.

But it didn't work well.

My work is like below.

How can I append rows and remove its (appended rows) contents?

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?

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

If you want to clone td as well, then you can do:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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