JQuery中具有不同事件的多个目标ID的相同功能

时间:2015-01-01 13:59:34

标签: javascript jquery

我有这个并且它正在工作:

function cancelFunction(targetid,e) {
    if (targetid.substring(0,9) == "editinput") {
        if (e.keyCode != 27) {
            return;
        }
        var target = targetid.substring(10);
    }
    else
        var target = targetid.substring(11);
    // DO OTHER STUFF HERE
}
$(\'[id^=editinput]\').keypress(function(e) {
    var targetid= $(this).attr("id");
    cancelFunction(targetid,e);
});
$(\'[id^=canceledit]\').click(function() {
    var targetid= $(this).attr("id");
    cancelFunction(targetid,"");
});

我想知道如果可以在keypress [id^=editinput]上合并click事件并在[id^=canceledit]上合并一次调用函数那之后呢?

我的意思是这样的(明显错误的语法):

$((\'[id^=canceledit]\').click)((\'[id^=editinput]\').keypress)(function(e) {
    var targetid = $(this).attr("id");
    if (targetid.substring(0,9) == "editinput") {
        if (e.keyCode != 27) {
            return;
        }
        var target = targetid.substring(10);
    }
    else
        var target = targetid.substring(11);
    // DO OTHER STUFF HERE
});

1 个答案:

答案 0 :(得分:2)

最简单的可能是重构一点

function cancelFunction(e) {
    if (this.id.substring(0,9) == "editinput") {
        if (e.keyCode != 27) {
            return;
        }
        var target = this.id.substring(10);
    } else {
        var target = this.id.substring(11);
    }
}

$('[id^=editinput]').on('keypress', cancelFunction);
$('[id^=canceledit]').on('click', cancelFunction);