如何在 jQuery 或纯 JavaScript 中添加额外的事件处理程序?
我有自己的带有 onShow()
函数的对象,当显示对象时(由我)调用该函数。我可以通过赋值覆盖这个函数
o.onShow = function() { // something };
,但它会删除函数的先前版本。因此,如果我希望保留现有的处理程序,我应该缓存它并调用新的处理程序:
o.oldOnShow = o.onShow;
o.onShow = function() { this.oldOnShow(); // something };
但这样我只能缓存一个以前的处理程序。如果有很多怎么办?
有没有一种方便的方法来完成这项任务?这项任务在文献中是如何命名的? jQuery 中有这样的方法吗?
I have my own object with onShow()
function, which is called (by me) when object is shown. I can override this function by assignment
o.onShow = function() { // something };
But it removes previous version of a function. So, if I wish to conserve existing handler, I should cache it and call in new handler:
o.oldOnShow = o.onShow;
o.onShow = function() { this.oldOnShow(); // something };
But this way I can cache only one previous handler. What if there are many of them?
Is there a convenient way to accomplish this task? How this task is named in literature? Is there a methods for this in jQuery?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 jQuery 中,您可以添加任意数量的处理程序:
后续调用不会删除先前绑定的处理程序。
In jQuery you can add as many handlers as you like:
Subsequent calls won't remove previously-bound handlers.
如果您需要触发自定义事件(如您定义的),您应该调用
.trigger()
方法(每当您认为应该触发该事件时):然后,使用
.bind()
或(如果您使用的是 jQuery 1.7+).on()
定义一个或多个侦听器:If you need to trigger a custom event (as in defined by you), you should call the
.trigger()
method (whenever you feel that event should be triggered):Then you define one or more listeners, using either
.bind()
or (if you're using jQuery 1.7+).on()
:您可以使用 jQuery 的绑定方法:
这会将事件处理程序添加到事件处理程序列表中,不会覆盖现有的处理程序。 这里是文档
You can use jQuery's bind method:
This adds an event handler to a list of event handlers, doesn't overwrite existing handlers. Here are the docs
通过 jQuery 附加事件处理程序不会与任何其他事件冲突,只要事件处理程序不会阻止事件传播。
如果您希望在本机 JavaScript 中完成此操作,则需要使用字符串连接:
Attaching an event handler via jQuery will not conflict with any other events, so long as the event handler does not stop the event from propagating.
If you'd rather accomplish this in native JavaScript, you need to use string concatenation:
如果你想用普通的 js 来做到这一点,那就有点棘手了。
当然,这样做的问题是,这只是更改了侦听器,而没有附加它。
但是,我们可以通过对代码稍加修改来附加一个新的侦听器:
通过这种方式,我们可以将多个函数附加到一个元素,而无需覆盖之前的函数。
If you're looking to do this with vanilla js, it's slightly more tricky.
The problem with this of course is that this simply changes the listener, and doesn't append it.
We can, however, append a new listener with a slight alteration to the code:
In this way, we're able to append multiple functions to an element without overriding the functions which were previously in place.