jQuery .keyPress() - 如何获取触发事件的输入值?
尝试做一些 jQuery 验证(没有插件 - 请不要回答“只需使用 validate-js 插件”)。
我正在为文档准备好的每个“必填字段”连接一个客户端事件处理程序 keypress :
$(document).ready(function() {
$('#myform input.required').each(function() {
$(this).keypress(onRequiredFieldKeyPress);
});
});
每次按键时都会正确触发此事件:
function onRequiredFieldKeyPress() {
if ($(this).val().trim() == '') {
$(this).next('em').html('*').show(); // show req field indicator
} else {
$(this).next('em').html('*').hide(); // hide req field indicator
}
}
但是 $(this).val() 始终为 null/空。看起来它正在传递一个“HTMLInputElement”,这正是我所期望的,但这几乎就像我必须将其投影到其他 jQuery 类型中?
本质上我正在尝试这样做:在我已连接的任何字段(都是输入元素)的按键事件上,调用该函数。在该函数中,如果该字段的值为“”(空),则显示一个隐藏字段,其中显示必填字段指示符。
我并不真正关心哪个实际元素触发了按键,因为我的逻辑行为是相同的。我只需要获取实际值。
我错过了什么吗?
Trying to do some jQuery validation (without the plugin - please no answers like "Just use the validate-js plugin").
I'm wiring up a client-side event handler keypress for each "required field" on doc ready:
$(document).ready(function() {
$('#myform input.required').each(function() {
$(this).keypress(onRequiredFieldKeyPress);
});
});
Which correctly fires this event on each keypress:
function onRequiredFieldKeyPress() {
if ($(this).val().trim() == '') {
$(this).next('em').html('*').show(); // show req field indicator
} else {
$(this).next('em').html('*').hide(); // hide req field indicator
}
}
But $(this).val() is always null/empty. Looks like it's passing in an "HTMLInputElement" which is what i'd expect, but it's almost like i have to project this into some other jQuery type?
Essentially i'm trying to do this: on the keypress event of any field which i have wired-up (which are all input elements), call that function. In that function, if that field has a value of '' (empty), then show a hidden field which displays a required field indicator.
I don't really care which actual element fired the keypress, as the behaviour of my logic will be the same. I just need to get the actual value.
Am i missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为你正在使用按键事件。按键有 3 个阶段:
1. 按键按下:按下按键时
2. 按键保持:按键被按住
3. 按键抬起:按键松开
在您的情况下,可以通过使用 keyup 事件来解决问题
Because you are using key-press event. Key press has 3 phase:
1. Key down: when key is press
2. Key hold: key is hold down
3. Key up: key is release
In your case, problem can be solved by using keyup event
尝试使用 event.currentTarget,其中 event 是函数的第一个参数。
请参阅此处:http://api.jquery.com/event.currentTarget
Try using event.currentTarget, where event is the first param of your function.
See here: http://api.jquery.com/event.currentTarget