使用相同的事件处理程序分别使用不同的事件绑定多个元素的优雅方法是什么? [英] What's the elegant way of binding multiple elements with different event respectively using same event handler?

查看:115
本文介绍了使用相同的事件处理程序分别使用不同的事件绑定多个元素的优雅方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有$(document)和$(window),它们分别与'ready'和'resize'事件绑定。他们正在共享相同的事件处理程序。

I have both $(document) and $(window), they are bound with 'ready' and 'resize' event respectively. They are sharing the same event handler.

代码:

$(window).on('resize', function () {    
     Shared code
});
$(document).ready(function () {
     Shared code
});

除了上面的风格外,还有一种传统的处理方式,使代码干净简单>

Instead of the style above, is there a conventional way of handling this to make the code clean and simple>

推荐答案

实际上这很简单。

var handler = function (event) {
    // Whatever you want to handle
};

$(window).on('resize', handler);
$(document).ready(handler);

这篇关于使用相同的事件处理程序分别使用不同的事件绑定多个元素的优雅方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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