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.

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.

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?

推荐答案

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


请注意,.on()实际上不会将事件绑定到目标,而是绑定到您要委托给的元素.因此,如果您有:

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

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

如果克隆ELEMENT#容器,则必须使用事件和数据进行深度克隆,才能保留使用.on()进行的绑定.

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

Jquery相关问答推荐

将选定2个AJAX结果显示到模板中

使用jquery将外部代码插入div

即使我使用 [FromBody] C# 从视图(Ajax)发送请求时在控制器中收到 NULL 对象

jQuery:在mousemove事件期间检测按下的鼠标按钮

加载外部 css 文件,如 jquery 中的脚本,这在 ie 中也兼容

jQuery .val() 和 .attr('value') 有什么区别?

提高 jQuery Select 器性能的好方法?

我如何从 ACE 编辑器中获得价值?

jQuery $.browser 是否已弃用?

如何使用 jQuery Select 的插件重置表单?

jQuery .load() 调用不会在加载的 HTML 文件中执行 JavaScript

使用 jquery 在 radio 上单击或更改事件

Twitter Bootstrap css 类的 jQuery show() 隐藏

如何使用jQuery触发类更改事件?

JavaScript 中的简单节流阀

jQuery.active 函数

如何使用 jQuery Validation Plugin 以编程方式判断表单是否有效

jquery $(window).width() 和 $(window).height() 在未调整视口大小时返回不同的值

textarea 的 val() 与 text()

小于 10 给数字加 0