如何在 javascript 中克隆表单并保留事件绑定

发布于 2024-09-02 03:14:31 字数 496 浏览 3 评论 0原文

我即将克隆表单的一部分,其中有一些绑定到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绝不放开 2024-09-09 03:14:31

不可以。您每次都必须重新添加处理程序。

如果您确实想避免这种情况,请使用事件委托 (delegate()live()) 附加事件处理程序。这样,它们在事件触发时不与特定节点对象相关联,而仅与元素的放置相关联,无论它们是否与选择器匹配。

$(myform).delegate('.dosomething', 'click', function() {
    // handle clicks on any .dosomething in the form now or added later
});

(并尽量避免对 html()/innerHTML 进行文本处理。这是不可靠的。最好迭代您想要更改其名称或类的对象attr。)

No. You would have to re-add handlers each time.

If you really want to avoid this, use event delegation (delegate() or live()) 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.

$(myform).delegate('.dosomething', 'click', function() {
    // handle clicks on any .dosomething in the form now or added later
});

(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 with attr.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文