是否有可能在全球范围内捕捉的keydown上动态地添加文本输入? [英] Is it possible to capture keydown globally on dynamically added text inputs?

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

问题描述

我用以下全局jQuery来显示和隐藏装载 DIV $ AJAX 要求:

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

然后,重置燮pressGlobal 为正常 $ AJAX 通话,这样的:

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 事件不会被绑定到全局函数。我也试过

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?

推荐答案

你将不得不使用 $(文件)。在()动态创建的控件。

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

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

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

你也可以使用: $('身体')上

解释: 当事件被指定,它只能分配给当前页面上不存在的元素。如果以后上的其他元素,没有什么看着那手表这些元素也使他们能够使用。      这就是为什么你需要的东西坐在文档级别是了解事件,并希望将其应用到的元素,以便它可以留意是否匹配任何新的元素,并应用该事件他们。

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天全站免登陆