且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jQuery检查是否在输入元素中输入了值

更新时间:2023-11-22 13:07:46

之所以需要将代码包装在document.ready包装器中的原因是,因为代码想要在其立即运行 已加载.通常,代码会在创建DOM之前运行(即页面已完全呈现),因此代码需要访问的某些元素尚不存在,并且代码会中断.

The reason for need to wrap code in a document.ready wrapper, is because the code wants to run instantly, the moment it is loaded. Usually, the code runs before the DOM has been created (i.e. the page has been fully rendered) -- so some of the elements the code needs to access are not there yet -- and the code breaks.

以下是使用document.ready包装器的示例:

Here is an example of using a document.ready wrapper:

HTML:

<div class="first-field">
    <input class="text" type="text" placeholder="Uw naam.." value="" />
    <svg class="unfilled" id="svg_user"></svg>
</div>

javascript/jQuery:

var ran=0;
$(document).ready(function() {

    $('.text').keyup(function(e) { 
        if (ran == 0){
            ran++;
            alert('test');
        }
    });

}); //END document.ready

正在使用jsFiddle

但是,如果HTML是通过javascript或AJAX(通过.load())或类似方式注入的,则用户事件将不会触发任何代码运行.

However, if the HTML has been injected via javascript or through AJAX (via .load()) or something like that, then the user events will not trigger any code to run.

在这种情况下,有一个简单的解决方案:使用jQuery的.on()方法.

In that case, there is a simple solution: use jQuery's .on() method.

var ran=0;
$(document).ready(function() {

    $(document).on('keyup', '.text', function(e) { 
        if (ran == 0){
            ran++;
            alert('test');
        }
    });

}); //END document.ready

上面的小变化:

$(document).on('keyup', '.text', function(e) { 

将事件处理程序绑定到文档本身,并告诉它监视涉及类.text的元素的所有keyup事件.

binds the event handler to the document itself, and tells it to watch for any keyup events involving the element with class .text.

修改了jsFiddle

其中一个应该可以正常工作.

One of those should work fine.

请注意,为您构造的示例包含一个CHECK,因此keyup操作不会被执行多次.您可以删除它,并让代码在每次按键时都执行某些操作:

Notice that the example constructed for you includes a CHECK so that the keyup action is not performed more than once. You can remove that and have the code do something with every keypress:

$(document).ready(function() {

    $('.text').keyup(function(e) { 
        alert('test');
    });

}); //END document.ready