use*_*627 12 jquery class enter keypress
我需要检测某人是否在具有特定类的文本输入中"输入".
我的jQuery如下:
$('input.large').keypress(function (e) {
if(e.which ==13)
console.log("pressed enter");
});
Run Code Online (Sandbox Code Playgroud)
我的HTML是这样的:
<tr><td> Personal Name </td></tr>
<tr><td> <input type='text' class='large'> </td></tr>
<tr><td> Email</td></tr>
<tr><td> <input type='text' class='large'> </td></tr>
Run Code Online (Sandbox Code Playgroud)
当我给出字段ID并尝试$('#elementid').keypress它工作.但这不起作用.我没有控制台输出.我错过了什么?
Dav*_*ues 13
您可以使用实时(.对()的)事件document与keydown(我认为这是更好).它允许您检测keydown与选择器匹配的当前和未来元素.
HTML:
<strong>Personal Name</strong>
<input type='text' class='large' /><br />
<strong>Email</strong>
<input type='text' class='large' />
?
Run Code Online (Sandbox Code Playgroud)
JS(使用jQuery 1.7+运行):
jQuery(document).on('keydown', 'input.large', function(ev) {
if(ev.key === 'Enter') {
// Will change backgroundColor to blue as example
this.style.backgroundColor = '#EFF';
// Avoid form submit
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
jsFiddle:http://jsfiddle.net/qvhWD/