简体   繁体   中英

clone table row

How can i use javascript (i assume) to clone a table row like ive beautifully illustrated in the picture below?

克隆行

You can hookup a live event to all the buttons. If you give them a class of clone for instance the following will work.

$('input.clone').live('click', function(){
   //put jquery this context into a var
   var $btn = $(this);
   //use .closest() to navigate from the buttno to the closest row and clone it
   var $clonedRow = $btn.closest('tr').clone();
   //append the cloned row to end of the table

   //clean ids if you need to
   $clonedRow.find('*').andSelf().filter('[id]').each( function(){
       //clear id or change to something else
       this.id += '_clone';
   });

   //finally append new row to end of table
   $btn.closest('tbody').append( $clonedRow );
});

Please Note: If you have elements in the table row with id's you will need to do a .each through them and set them to a new value otherwise you will end up with duplicate id's in the dom which is not valid and can play havoc with jQuery selectors

You can do this like so

If you want a really simple solution, just use innerHTML:

var html = document.getElementById("the row").innerHTML;

var row = document.createElement('p');

row.innerHTML= html;

document.getElementById("table id").appendChild(row);

For what purpose do you want to use the data? I've done similar things previously on data input forms and generally I've found it to be beneficial to the users not to manipulate everything in Javascript but to hook to store the data on the server and interface with AJAX.

The issue is that as soon as you start letting users do this sort of complex table manipulation and they accidentally hit the back button you end up with a lot of disgruntled punters. Coding up transient storage on a database isn't that much harder than manipulating Javascript and in fact can be easier as you can break the operations down more easily. Debugging is simpler for that reason too (you always have inspect access to the current state of your table).

Lots of option for handling via AJAX - the simplest being to just use a place-holder division and feed the whole table structure in as needed.

A jQuery example:

$(document).ready(function(){
   $('TABLE.recs').delegate('INPUT.clone','click',function(e){
     e.preventDefault();
     var s = $(this).parent().parent().clone().wrap('<div>').parent().html();
     $('TABLE.recs TBODY TR:last').after(s);
   });
});

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