这里是 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/