简体   繁体   中英

Is it possible to capture keydown globally on dynamically added text inputs?

I'm using the following global jQuery to show and hide a loading div for $.ajax calls:

$(document).ajaxStart(function(){
    $("#loading").show();
}
$(document).ajaxStop(function(){
    $("#loading").hide();
}

This works fine, but I do not want to show the loading div for autocompletes, so I added this:

$("input[type=text]").keydown(function(){
    if($(this).hasClass('ui-autocomplete-input')) {
        window.suppressGlobal = true;
    }
});

Then, to reset suppressGlobal for "normal" $.ajax calls, this:

var origAjax = $.ajax;
$.ajax = function() {
    if (window.suppressGlobal) {
        arguments[0].global = false;
    }
    origAjax.apply(this, arguments);
    window.suppressGlobal = false;
};

This all works nicely for text inputs that are constructed with page load. However, I have several situations where text inputs are inserted dynamically on the client-side using jQuery/Javascript, in which case the keydown event does not get bound to the global function . I also tried on :

$("input[type=text]").on('keydown', function(){
    if($(this).hasClass('ui-autocomplete-input')) {
        window.suppressGlobal = true;
    }
});

But that doesn't work either. Is there a way that I can globally capture the keydown event regardless of when the text input was added? Could I somehow globally capture the addition of text inputs to the DOM and attach the event handler then?

you will have to use $(document).on() for dynamically created controls.

jsfiddle: http://jsfiddle.net/G9qJE/

also you can use: $('body').on

explanation: When an event is assigned, it's only assigned to elements that currently exist on the page. If you later on other elements, there is nothing watching that watches for those elements too allow them to be used as well. That is why you need something sitting at the document level which is aware of the event and the elements you want to apply it to, so that it can watch for any new elements that match and apply that event to them as well.

 $(document).on("keydown", "input[type=text]", function() { 
        if($(this).hasClass('ui-autocomplete-input')) {
            window.suppressGlobal = true;
        }

    });

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