JQuery clone()没有克隆事件绑定,甚至没有使用 on()

我已经创建了一系列用于移动 web 应用程序的自定义 jQuery 事件。它们工作得很好,并且经过了测试。然而,我遇到了一个我难以理解的小问题。

我在 DOM 中的一些元素上使用 .clone(),这些元素包含一个按钮。该按钮有一些绑定到它的自定义事件(这些事件使用 .on()绑定) ,但是。不幸的是,当我使用 jQuery 的 .clone()时,绑定没有得到保留,我必须再次添加它们。

以前有人遇到过这种情况吗,有人知道这附近有什么潜在的工作吗?我认为使用 .on()应该保留现在或将来存在的元素的绑定?

76086 次浏览

I think you should use this overload of the .clone() method:

$element.clone(true, true);

clone( [withDataAndEvents] [, deepWithDataAndEvents] )

withDataAndEvents: A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false.

deepWithDataAndEvents: A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false).


Beware that .on() does not actually bind the events to the targets but to the element you are delegating to. So if you have:

$('#container').on('click', '.button', ...);

The events are actually binded to #container. When a click on a .button element occurs, it bubbles up to the #container element The element which triggered the event is evaluated upon the selector parameter of .on() and if it matches, the event handler is executed. This is how event delegation works.

If you clone the element #container, you have to deep clone with events and data for the bindings made with .on() to be preserved.

This would not be necessary if you were using .on() on a parent of #container.