简体   繁体   中英

How to fire one function for two separate events in js?

I have 2 events, a keydown and a click. I would like to put them into a single function and when the function is called, whichever event was fired would do what it's supposed to.

Example:

var close = function () {
    $('.alert').remove();
};

$(document).on('keydown', function (event) {
    if (event.keyCode === 27) {
        //27 = ESC
        close();
    }
});

$('.alertBG').on('click', function () {
    close();
});

I can't think of a way to get the document and .alertBG parts to play nicely. ( Fiddle )

Don't. Your functions are too different. You have already factored the reusable parts of them out into a close function that you call from both. This is the best way to do it.


If you really wanted to, then you would have to bind a click/keydown handler to document and test the type of event and the element.

$(document).on("keydown click", function (event) {
    if (
    (event.type === "keydown" && event.keyCode === 27) || (event.type === "click" && (
    $(event.target).is(".alertBG") || $(event.target).parents(".alertBG").length))) {
        close();
    }
});

As you can see, it's much cleaner just to bind your event handlers separately when there are so many differences between them.

Do you mean something like this?

function handler(event) {
    if(event.type === "click") {
        close();
    } else if(event.type === "keydown") {
        if (event.keyCode === 27) {
            //27 = ESC
            close();
        }
    }
}

$(document).on('keydown', handler);
$('.alertBG').on('click', handler);

Anything like this ?

function myFunc(method){
    if(method == "one"){
       // do anything
    }
    else if(method == "other"){
       // do other thing
    }
}

$(document).on('keydown', function (event) {
    if (event.keyCode === 27) {
       myFunc("one");
    }
});

$('.alertBG').on('click', function () {
    myFunc("other");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM