使用jQuery off()。on()或仅使用on() [英] Using Jquery off().on() or just on()
问题描述
我知道我们可以使用jQuery on()
函数附加事件,并使用 off()
。
I know that we can attach events with the jQuery on()
function and remove them again with off()
.
在一个现有项目中,我有时会遇到类似于以下代码:
In an existing project I do sometimes come across code similar to this:
$("#SomeId").off("click").on("click");
或者有时使用类似以下的命名空间时:
or sometimes when using namespacing similar to this:
$("#SomeId").off("click.namespace").on("click.namespace");
据我所知,您只能将单个事件附加到事件。
例如,如果我只是对 on( click)
进行操作指定的功能,覆盖当前分配的功能,并添加到 click事件中。
For example if I simply do on("click")
it will attach my specified function, overwriting the current function assigned, adding to the "click" event.
如果我在 on( click.namespace)
上执行操作,它将附加我指定的函数覆盖当前功能已分配,添加到 click.namespace
。
If I do on("click.namespace")
it will attach my specified function overwriting the current function assigned, adding to the click.namespace
.
删除所有事件的意义是什么通过将 off( click)
链接到 on( click)
,如果 on ()
已经替换了分配给指定event / event.namespace的所有函数吗?
What is the point removing any events by chaining an off("click")
to the on("click)
if on()
already replaces any functions assigned to the specified event/event.namespace?
我们的代码中是否存在多余的语法,或者是有原因的?
Is it redundant syntax in our code or is there a reason for it which I have missed?
编辑-谢谢 kapa
我现在有点傻了,我更正了我上面的错误知识。执行 on( click.namespace1)
几次,现在我观察到 data( events)
对象不断添加到点击事件数组中。
Edit - Thank you kapa
I feel a bit silly now, I corrected my faulty knowledge above. Executing on("click.namespace1")
several times I observed now that the data("events")
object kept adding to the click event array.
我认为这可以回答我自己的问题。这就是为什么要使用 off( event.namespace)
来确保没有附加任何东西的原因确切的事件/event.namespace。
I think that answers my own question there. That is why one would use off("event.namespace")
to ensure nothing else is attached to that exact event/event.namespace.
推荐答案
实际上,您可以将多个事件处理程序附加到同一事件,而不仅仅是一个。即使使用名称空间。查看此快速演示。
Actually you can attach multiple event handlers to the same event, not just one. Even when namespaces are used. Check out this quick demo.
实际上,一个命名空间的优点在于,您可以标记一组事件处理程序,并在以后轻松删除它们,以避免多次附加它们。这是此行的作用:
Actually, one advantage of namespaces is that you can mark a group of event handlers, and easily remove them later to avoid attaching them several times. This is what this line does:
$("#SomeId").off("click.namespace").on("click.namespace");
这篇关于使用jQuery off()。on()或仅使用on()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!