简体   繁体   English

添加键码事件处理程序后如何删​​除?

[英]How to remove a keycode event handler once it has been added?

How can I remove a keypress event handler after I have set one for an element? 为元素设置一个按键事件处理程序后,如何删除它?

I have a search box with the id #sb that lists search suggestions upon typing via autocomplete, and then goes to the very first suggestion upon pressing enter if there is one. 我有一个ID为#sb的搜索框,其中列出了通过自动完成功能键入时的搜索建议,如果有,则在按Enter时转到第一个建议。

It works fine if the user enters a search string which does not exist. 如果用户输入了不存在的搜索字符串,它将很好地工作。 Pressing ENTER goes nowhere as it should. 按ENTER并没有应有的结果。

However, if a valid search suggestion is returned, and then the user changes their mind and decides to search for another string for which there is no search suggestion... pressing ENTER still goes to the previously suggested search result. 但是,如果返回了有效的搜索建议,然后用户改变了主意,并决定搜索没有搜索建议的另一个字符串...按ENTER仍将转到先前建议的搜索结果。

For example, if the user searches for "hot dogs", deletes that entirely, and then searches for "asgdoksadjgoawhet" then upon pressing enter they will be redirected to http://example.com/hot-dogs , when in fact nothing should happen. 例如,如果用户搜索“热狗”,将其完全删除,然后搜索“ asgdoksadjgoawhet”,则在按Enter时,他们将被重定向到http://example.com/hot-dogs ,而实际上什么都不应该发生。

Below is the response section of my autocomplete code: 以下是我的自动填充代码的响应部分:

    response: function( event, ui ) {

        if(typeof ui.content[0] == 'undefined') {

            //no search results exist

            //make enter do nothing
            $('#sb').keypress(function(e) {
                if(e.which == 13) {
                    e.preventDefault(); //does not work
                    $('#sb').off('keypress', '#sb'); //does not work, either
                }
            });

        } else {

            //search results exist

            //make ENTER go to the first suggested result
            $('#sb').on('keypress', function(e) {
                if(e.which == 13) {
                    window.location.href = 'http://example.com/'+ui.content[0].id;
                }
            });

        }
    }

Should I not be using anonymous functions, perhaps? 也许我不应该使用匿名函数?

$( "#foo" ).bind( "click", handler );

function handler(){
  //do the stuff
}

//after some condition
$( "#foo" ).unbind( "click", handler );

Bind the reference of function to event callback, so you can later use it to unbind. 将函数的引用绑定到事件回调,以便以后可以使用它来取消绑定。

    $('#sb').on("keypress", function(e) {
        if(e.which == 13) {
            $(this).off(e);
        }
    });

If you want to unbind it directly after use you can use .one 如果要在使用后直接解除绑定,可以使用.one

This will fire the event only once: 这只会触发一次事件:

$('#sb').one('keypress', function(e) {
    if(e.which == 13) {
        //do stuff
        }
    });

If you however want to unbind the event at any other time you can do this: 但是,如果您想在其他任何时间取消绑定事件,则可以执行以下操作:

var kbEvent = $('#sb').on('keypress', function(e) {
            if(e.which == 13) {
                //do stuff
            }
        });

.... some other code ...
$('#sb').off(kbEvent);

$('#sb').off('keypress', '#sb'); removes the event handler on the child elements '#sb' of the element '#sb'. 删除元素“ #sb”的子元素“ #sb”上的事件处理程序。

$('#sb').off('keypress'); removes the event handler on '#sb'. 删除“ #sb”上的事件处理程序。

Another exemple $( "#dataTable tbody" ).on( "click", "tr", function() { //... }); 另一个例子$( "#dataTable tbody" ).on( "click", "tr", function() { //... }); adds an event handler on each tr elements in "#dataTable tbody" 在“ #dataTable tbody”中的每个tr元素上添加事件处理程序

$( "#dataTable tbody" ).off( "click", "tr"); removes it from each tr elements in "#dataTable tbody" 从“ #dataTable tbody”中的每个tr元素中删除它

Try this little example it shows you how to bind and unbind an event. 试试这个小例子,它向您展示了如何绑定和解除绑定事件。

html HTML

<div>
    <input id="bind_me"/>
    <div>
    </div>
</div>

jQuery code jQuery代码

$('#bind_me').on('keypress', function(e)
{
    if(e.which==='q'.charCodeAt(0) || e.which==='q'.charCodeAt(0) )
    {
        $('#bind_me').off('keypress');
    }
    var tmp = $(this).next().text();
    $(this).next().text(tmp+String.fromCharCode(e.which));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM