如何在js中为两个单独的事件触发一个函数?

时间:2015-07-23 12:07:46

标签: javascript jquery

我有2个事件,一个keydown和一个点击。我想把它们放到一个函数中,当函数被调用时,无论发生什么事件都会做它应该做的事情。

示例:

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

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

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

我无法想办法让document.alertBG部分很好地发挥作用。 (Fiddle

3 个答案:

答案 0 :(得分:3)

别。你的功能太不一样了。您已经将它们的可重用部分分解为close函数,您可以从这两个函数中调用它们。这是最好的方法。

如果你真的想,那么你必须将click / keydown处理程序绑定到document并测试事件的类型和元素。

$(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();
    }
});

正如您所看到的,当它们之间存在很多差异时,单独绑定事件处理程序会更加清晰。

答案 1 :(得分:2)

你的意思是这样吗?

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);

答案 2 :(得分:0)

有这样的吗?

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");
});
相关问题