克隆表行

mrp*_*atg 5 html javascript jquery mootools

我如何使用javascript(我假设)来克隆像下面图片中精美插图的表格行?

克隆行http://i28.tinypic.com/2yyuz61.png

red*_*are 12

您可以将实时事件连接到所有按钮.如果你给他们一个克隆类,例如以下将工作.

$('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 );
});
Run Code Online (Sandbox Code Playgroud)

请注意: 如果表格行中的元素包含id,则需要通过它们执行.each并将它们设置为新值,否则最终会在dom中出现重复的id,这是无效的并且可能会造成严重破坏jQuery选择器

你可以这样做