简体   繁体   中英

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.

It works fine if the user enters a search string which does not exist. Pressing ENTER goes nowhere as it should.

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.

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.

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

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').off('keypress'); removes the event handler on '#sb'.

Another exemple $( "#dataTable tbody" ).on( "click", "tr", function() { //... }); adds an event handler on each tr elements in "#dataTable tbody"

$( "#dataTable tbody" ).off( "click", "tr"); removes it from each tr elements in "#dataTable tbody"

Try this little example it shows you how to bind and unbind an event.

html

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

jQuery code

$('#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));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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