javascript - 单击文本输入时该怎么做?

标签 javascript jquery text input focus

这里是 jQuery 的初学者,我假设这个问题的答案很简单,所以我道歉。

我有一个像这样的登录表单:

<table id="login_form">
    <tr>
        <td class="login_label">Username: </td>
        <td><input type="text" class="login_input" /></td>
    </tr>
    <tr>
        <td class="login_label">Password: </td>
        <td><input type="password" class="login_input" /></td>
    </tr>
</table>

和 jQuery 代码:

$(".login_input")
    .focus(function(){
        alert("Why do I never get this alert?");
    }
);

为什么当我单击两个文本输入字段中的任何一个时,不显示警报?如果我将“焦点”更改为“就绪”,那么我会收到警报,因此我假设这与此有关。

最佳答案

您需要输入document.ready这样,当元素添加到 DOM 并且 DOM 准备就绪时,就会执行绑定(bind)代码。 Ready 在您的代码中工作,因为它等待将元素添加到 DOM 中。

<强> Live Demo

$(document).read(function(){
   $(".login_input").focus(function(){
        alert("Why do I never get this alert?");
    });
});

The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts, reference.

关于javascript - 单击文本输入时该怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20016908/

相关文章:

javascript - 功能性 react 组件上的窗口对象出现问题

javascript - jshint ignore 使用 '!==' 与 '' 进行比较

javascript - Mongo 中的 Meteor 数据在哪里?

python - 几乎相同的副本,只是长度不同

java - 在 Google App Engine (Java) 中将文本写入图像

ios - 检测传入的iMessage消息或文本消息-iOS

javascript - 如何计算一个函数被唯一调用了多少次

asp.net - 访问 offsetParent 时 IE 6/7 "Unspecified Error"错误是否有解决方法

jquery - 如何在响应式网站上将元素与背景对齐

javascript - 单击时图像源中的数字递增