是否可以在动态添加的文本输入上全局捕获 keydown? [英] Is it possible to capture keydown globally on dynamically added text inputs?

查看:19
本文介绍了是否可以在动态添加的文本输入上全局捕获 keydown?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下全局 jQuery 来显示和隐藏 $.ajax 调用的加载 div:

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

这很好用,但我不想显示自动完成的加载 div,所以我添加了这个:

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;
    }
});

然后,为正常"$.ajax 调用重置suppressGlobal,这个:

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;
};

这对于使用页面加载构建的文本输入非常有效.但是,我有几种情况使用 jQuery/Javascript 在客户端动态插入文本输入,在这种情况下 keydown 事件不会绑定到全局函数.我也试过 on:

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;
    }
});

但这也行不通.有没有一种方法可以全局捕获 keydown 事件,而不管文本输入何时添加?我能否以某种方式全局捕获添加到 DOM 的文本输入并附加事件处理程序?

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?

推荐答案

你将不得不使用 $(document).on() 来动态创建控件.

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

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

你也可以使用:$('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;
        }

    });

这篇关于是否可以在动态添加的文本输入上全局捕获 keydown?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆