开发者

Unbind special keypress event

开发者 https://www.devze.com 2023-04-06 23:13 出处:网络
I\'ve got a question regarding jQuery keypress events. I\'ve got the following (working) code: $(document).bind(\'keypress\', function(event) {

I've got a question regarding jQuery keypress events. I've got the following (working) code:

$(document).bind('keypress', function(event) {

    if ($('#myDiv').is(':visible')) {

        if (event.which == 102) {
            // ...do something...
        }

    }
    else {
        if (event.which == 102) {
            return;
        }
    }

});

I always "unbind" the event with binding another "over" it. I know that I can unbind it with .unbind('keypress') but I got more keypress events and when i unbin开发者_如何学God this with $(document).unbind('keypress') all my events get lost.

Can I do something like "keypress.102" to only unbind this particular "key" or how can this be done?!


You were on the right track. That's called namespaced events, i.e. labelling specific bindings using <event_name>.<namespace> (in your case, "keypress.102").

For example:

$(document).bind("keypress.key102", function(event) {
    if ($('#myDiv').is(':visible')) {

        if (event.which == 102) {
            // ...do something...
        }

    }
    else {
        if (event.which == 102) {
            return;
        }
    }
});

you can later unbind that without affecting other bound keypress events:

$(document).unbind("keypress.key102");


Use a namespaced event.

http://docs.jquery.com/Namespaced_Events

0

精彩评论

暂无评论...
验证码 换一张
取 消