如何在 javascript 中克隆表单并保留事件绑定
我即将克隆表单的一部分,其中有一些绑定到 click
事件的操作。我想将属性中出现的所有单词 TEMPLATE
更改为 'n_'+ID
。我想从克隆部分的结构中进行抽象 - 它将是一个 TEMPLATE 或 10 个。 我尝试了类似的操作,但绑定丢失了:
insert = function(){
var old = $('#TEMPLATE');
var copy = old.clone(true);
var html = old.html().replace(/TEMPLATE/g,'n'+next_ID);
old.html(html);
old.attr('id','n'+next_ID);
old.show('fast');
old.after(copy);
next_ID++;
}
有没有什么方法可以在不了解复制元素的结构的情况下轻松完成此操作。
I am about to clone a part of form which has some actions bound to click
events. I want to change all occurences of word TEMPLATE
in attributes to 'n_'+ID
. I want to abstract from structure of cloned part - It would be one TEMPLATE
or 10.
I tried to something like this but the bindings are lost:
insert = function(){
var old = $('#TEMPLATE');
var copy = old.clone(true);
var html = old.html().replace(/TEMPLATE/g,'n'+next_ID);
old.html(html);
old.attr('id','n'+next_ID);
old.show('fast');
old.after(copy);
next_ID++;
}
Is there any way to do it easily without knowing anything about the structure of the copied element.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不可以。您每次都必须重新添加处理程序。
如果您确实想避免这种情况,请使用事件委托 (
delegate()
或live()
) 附加事件处理程序。这样,它们在事件触发时不与特定节点对象相关联,而仅与元素的放置相关联,无论它们是否与选择器匹配。(并尽量避免对
html()
/innerHTML
进行文本处理。这是不可靠的。最好迭代您想要更改其名称或类的对象attr
。)No. You would have to re-add handlers each time.
If you really want to avoid this, use event delegation (
delegate()
orlive()
) to attach your event handlers. That way they are not associated with particular node objects, but only the placement of elements, whether they match a selector, at event firing time.(And try to avoid text processing over the
html()
/innerHTML
. This is unreliable. It's better to iterate over objects whose names or classes you want to change doing it withattr
.)