使用 jQuery“clone()”后,如何维护(或重新应用)新元素上的 jQuery 绑定?
我有一个表单,我使用 jQuery“.clone()”来添加新行。一切看起来都很棒,但是我有一个绑定问题。基本上,在初始化时,我对一个字段使用 jQuery“.datepicker()”函数(基于类)。如果我单独使用“.clone()”,我不会获得新项目的任何“.datepicker()”功能。如果我使用“.clone(true)”,我会获得该功能,但对于克隆的行,它会填充从中克隆的行的日期,而不是单击的实际行。
我尝试过解除绑定/重新绑定,但这些都不起作用。那么,如何将新行附加到表单,同时仍然让所有 jQuery 乐趣正常工作?
最佳
编辑1 (jQuery):
function addLineItem(){ $('#charges_table tr:last').clone(true).insertAfter('#charges_table tr:last'); } $(function(){ $('.date_pick').datepicker({"numberOfMonths": 2}); $("#add_line_item").bind('click',function(event){ event.preventDefault(); addLineItem(); $('.date_pick').datepicker('destroy'); $('.date_pick').datepicker(); }) })
仅供参考,我只绑定到类上,并且 HTML 元素不使用 ID 来说话。
I have a form with which I use jQuery ".clone()" to add new rows. Everything looks great, however I have a binding problem. Basically, on initialization, I use the jQuery ".datepicker()" function for one field (based on class). If I use ".clone()" by itself I don't get any of the ".datepicker()" functionality with the new item. If I use ".clone(true)" I get the functionality, but for cloned rows it fills the date of the row it was cloned from, not the actual row clicked.
I've tried unbinding/rebinding, but none of this works. So, how do I append new rows to a form while still getting all of the jQuery funness to work properly?
Best
EDIT 1 (jQuery):
function addLineItem(){ $('#charges_table tr:last').clone(true).insertAfter('#charges_table tr:last'); } $(function(){ $('.date_pick').datepicker({"numberOfMonths": 2}); $("#add_line_item").bind('click',function(event){ event.preventDefault(); addLineItem(); $('.date_pick').datepicker('destroy'); $('.date_pick').datepicker(); }) })
FYI, I'm only binding on class, and the HTML elements aren't using an ID to speak of.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您
.clone()
时,您是否在将元素插入回 DOM 之前更改元素的 ID?如果没有,您的 ID 就会重复,这可能会成为您麻烦的根源。When you
.clone()
, are you changing the ID of the element before you insert it back into the DOM? If not, your ID would be duplicated, and that could be the source of your trouble.首先,正如所写,您的方法 addLineItem 始终会克隆表的最后一行:
$('#charges_table tr:last')
。听起来您想克隆发生单击的表行。如果是这种情况,那么类似这样的事情应该可以解决问题:我还没有测试过这段代码,但它基于我的一个项目中类似的表行克隆代码。
First, as written, your method addLineItem is always going to clone whatever the last row of the table is:
$('#charges_table tr:last')
. It sounds like you want to clone the table row within which the click occurred. If that is the case, then something like this should do the trick:I haven't tested this code, but it is based on similar table row cloning code in one of my projects.