Bind multiple events to same function

强颜欢笑 提交于 2020-01-04 13:05:27

问题


How can I bind mutiple events to the same function. I want click and touchstart to do the same. And then I want a second function for mouseover. I would like to use this kind of setup:

    $(document).on({
        click: function (event) {
        // I want this: click, touchstart: function (event) {
            event.preventDefault();
            // do something         
        },
        mouseover: function (event) {
            event.preventDefault();
            // do something         
        }
    }, '.link');

回答1:


You can combine the events in one .on() with space:

$(document).on('click touchstart', function(e) {
    // this will be called on click as well as touchstart
});



回答2:


There's no reason why you can't call an external function instead:

function myExternalFunction (event) {
    // do stuff
}

$(document).on({
    click: myExternalFunction,
    mouseover: myExternalFunction
}, '.link');



回答3:


According to the .on() documentation (and confirmed via a quick look at the .on() implementation) you could do this:

$(document).on({
    "click touchstart" : function (event) {
        event.preventDefault();
        // do something         
    },
    mouseover: function (event) {
        event.preventDefault();
        // do something         
    }
}, '.link');

Demo: http://jsfiddle.net/XzkTm/



来源:https://stackoverflow.com/questions/17425311/bind-multiple-events-to-same-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!