jQuery克隆表行 [英] jQuery Clone table row

查看:141
本文介绍了jQuery克隆表行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子,最后有一个添加按钮.当您单击此按钮时,我希望在当前表的下面创建一个新表行.我还希望此行上的输入字段为空白.我正在尝试使用.clone()进行此操作,但它会克隆页面上的所有行.请帮忙.谢谢

I have a table with an Add button on the end. When you click this button I want a new table row to be created underneath the current one. I also want the input fields on this row to be blank. I am trying to do this using .clone() but it clones all the rows on the page. Please help. Thanks

脚本

$("input.tr_clone_add")
        .live('click', function(){
              $(this).closest('.tr_clone')
                    .clone()
                    .insertAfter(".tr_clone")
         });

HTML

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data">
<tr>
<td>Name</td>
<td>Location</td>
<td>From</td>
<td>To</td>
<td>Add</td>
</tr>
<tr class="tr_clone">
<td><input type="text" autofocus placeholder="who" name="who" ></td>
<td><input type="text" autofocus placeholder="location" name="location" ></td>
<td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"></td>
<td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"></td>
<td><input type="button" name="add" value="Add" class="tr_clone_add"></td>
</tr>
</table><!-- /table#table-data -->

推荐答案

您的问题是您的 insertAfter :

Your problem is that your insertAfter:

.insertAfter(".tr_clone")

在每个.tr_clone之后插入:

匹配的元素集将插入到此参数指定的元素之后.

the matched set of elements will be inserted after the element(s) specified by this parameter.

您可能只想在要复制的行上使用 after .还有一点.find(':text').val('')会清除克隆的文本输入;像这样的东西:

You probably just want to use after on the row you're duplicating. And a little .find(':text').val('') will clear the cloned text inputs; something like this:

var $tr    = $(this).closest('.tr_clone');
var $clone = $tr.clone();
$clone.find(':text').val('');
$tr.after($clone);

演示: http://jsfiddle.net/ambiguous/LAECx/

我不确定哪个输入应该以焦点为结尾,所以我将其保留下来.

I'm not sure which input should end up with the focus so I've left that alone.

这篇关于jQuery克隆表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆