How to unbind keydown event for some time and then bind it again in Jquery?

假装没事ソ 提交于 2020-01-06 18:12:19

问题


I am using arrow key navigation for table. Based on current selected row I have to load some details in a div. after selecting a row it will make Ajax call to server to get more details and load that detail in a div. This might take some time to make Ajax call and and update div. Within this time I want to disable key down event.

     $('#tbl tbody').on('keydown', function (event) {

        var keyCode = event.keyCode;

        if (keyCode >= 37 && keyCode <= 40) {
            event.preventDefault();
            ChangeTarget(keyCode)
        }
    });

I just want to unbind or suspend keydown event just for some time.

i tried to use time out but that is not helping me as i want.

$('#tbl tbody').on('keydown', function (event) {
            var keyCode = event.keyCode;

            if (keyCode >= 37 && keyCode <= 40) {
                event.preventDefault();
                ChangeTarget(keyCode);
                setTimeout(function () {
                }, 10000);
            }
        });

i don't want to record any key event until Ajax complete its job !!!


回答1:


You can use a boolean flag instead of unbind.

Here is an example:

var keyNavigationDisabled = false;

$('#tbl tbody').on('keydown', function (event) {
    if (keyNavigationDisabled) return;
    var keyCode = event.keyCode;
    if (keyCode >= 37 && keyCode <= 40) {
        event.preventDefault();
        ChangeTarget(keyCode)
    }
});

function getRemoteData() {
    keyNavigationDisabled = true;
    $.ajax({
        url: 'http://example.com',
        complete: function () {
           keyNavigationDisabled = false;
        }
    });
}


来源:https://stackoverflow.com/questions/14375271/how-to-unbind-keydown-event-for-some-time-and-then-bind-it-again-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!