jQuery clone()没有克隆事件绑定,即使是on() [英] jQuery clone() not cloning event bindings, even with on()

查看:381
本文介绍了jQuery clone()没有克隆事件绑定,即使是on()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一系列用于移动Web应用程序的自定义jQuery事件。它们运行良好且经过测试。但是,我遇到了一个小问题,我无法理解。

I have created a series of custom jQuery events for use in mobile web applications. They work great and have been tested. However, I have run into a small problem which I am having trouble understanding.

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

I am using .clone() on a few elements within the DOM, which contain a button. The button has some of the custom events bound to it (the events are bound using .on()), but. Unfortunately, when I use jQuery's .clone(), the bindings are not preserved, and I have to add them again.

之前是否有人遇到此问题,是否有人知道潜在的工作?我认为使用 .on()应该保留现在或将来存在的元素的绑定吗?

Has anyone encountered this before, does someone know of a potential work around? I thought that using .on() was supposed to preserve the binding for elements that exist now, or in the future?

推荐答案

我认为你应该使用 .clone()的重载方法:

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

$element.clone(true, true);




clone([withDataAndEvents] [,deepWithDataAndEvents])

withDataAndEvents :一个布尔值,指示是否应将事件处理程序和数据与元素一起复制。默认值为false。

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

deepWithDataAndEvents :一个布尔值,指示是否应复制克隆元素的所有子项的事件处理程序和数据。默认情况下,它的值与第一个参数的值匹配(默认为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).






请注意 .on()实际上并不将事件绑定到目标,而是绑定到您委派给的元素。所以如果你有:


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', ...);

事件实际绑定到 #container 。当点击 .button 元素时,它会冒泡到 #container 元素触发事件的元素根据 .on()的选择器参数进行计算,如果匹配,则执行事件处理程序。这就是事件委托的工作方式。

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.

如果克隆元素#container,则必须使用进行绑定的事件和数据进行深度克隆.on()要保留。

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

如果您使用的是 .on()在父母 #container

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

这篇关于jQuery clone()没有克隆事件绑定,即使是on()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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