克隆表行

问题描述 投票:5回答:4

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

clone row

javascript jquery html mootools
4个回答
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 );
});

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

你可以这样做


0
投票

如果你想要一个非常简单的解决方案,只需使用innerHTML:

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

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

row.innerHTML= html;

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

0
投票

您想用于什么目的的数据?我以前在数据输入表单上做过类似的事情,通常我发现它对用户不利于操纵Javascript中的所有东西,而是钩住将数据存储在服务器上并与AJAX接口。

问题是,一旦你开始让用户进行这种复杂的表格操作,他们不小心点击了后退按钮你最终会遇到很多不满的投注者。编写数据库上的瞬态存储并不比操作Javascript困难得多,事实上可以更容易,因为您可以更轻松地打破操作。由于这个原因,调试也更简单(您始终可以检查表的当前状态)。

通过AJAX处理的选项很多 - 最简单的方法就是使用占位符分区并根据需要提供整个表结构。


0
投票

一个jQuery示例:

$(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);
   });
});
© www.soinside.com 2019 - 2024. All rights reserved.