简体   繁体   English

是否可以全局捕获动态添加的文本输入上的按键按下?

[英]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: 我正在使用以下全局jQuery来显示和隐藏$.ajax调用的加载div

$(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: 这可以正常工作,但是我不想显示自动完成的加载div,所以我添加了以下内容:

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

Then, to reset suppressGlobal for "normal" $.ajax calls, this: 然后,重置suppressGlobal为“正常” $.ajax调用,这样的:

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 . 但是,在几种情况下,文本输入是使用jQuery / Javascript在客户端动态插入的,在这种情况下keydown事件不会绑定到全局函数 I also tried on : 我也试过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? 有没有一种方法可以全局捕获keydown事件,而不管何时添加了文本输入? Could I somehow globally capture the addition of text inputs to the DOM and attach the event handler then? 我可以以某种方式全局捕获到DOM的文本输入的附加内容,然后附加事件处理程序吗?

you will have to use $(document).on() for dynamically created controls. 您将必须使用$(document).on()来动态创建控件。

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

also you can use: $('body').on 也可以使用: $('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;
        }

    });

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

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