我可以在密钥功能中绑定密钥吗?

时间:2014-01-26 22:43:35

标签: jquery javascript-events

我已经为某些功能绑定了几个键。应用程序中有一点应该暂时禁用这些绑定,然后在退出此临时状态时重新激活。我能够绑定密钥,进入临时状态,取消绑定密钥,执行操作,重新绑定单个密钥,对该密钥的keyup事件执行操作,但重新绑定原始密钥不起作用。是否可以在键盘功能中绑定键?任何帮助将不胜感激,谢谢!

function bindKeys() {  
    $(document).keyup(function() {
        if ( event.which == 27 ) {
            //stuff
        }

        if ( event.which == 32 ) {
            //stuff
        }

        if ( event.which == 37 ) {
            //stuff
        }
    });
}

function temporaryUnbind() {  
    $(document).keyup().unbind();
        //stuff
    $(document).keyup(function() {
        if ( event.which == 27 ) {
            //stuff
            bindKeys();
        }
    });
}

1 个答案:

答案 0 :(得分:3)

完全可以使用onoff,然后再使用on来完成此操作。

简单地使用on然后在代码中使用一个标志来告诉您是否在on处理程序中处理事物可能更简单。

再次使用onoffon

function handleKeyUp() {
    // Handle your keys
}

// When you should start handling the keys
$("some selector").on("keyup.myhandler", handleKeyUp);

// When you should temporarily stop handling the keys
$("some selector").off("keyup.myhandler");

// When you should start again (same as the original start)
$("some selector").on("keyup.myhandler", handleKeyUp);

使用旗帜:

var flag = true;
$("some selector").on("keyup.myhandler", function() {
    if (flag) {
        // Handle your keys...
    }
});

// When you should temporarily stop handling the keys
flag = false;

// When you should start again (same as the original start)
flag = true