检测输入某个类的输入元素

我需要检测某人是否在具有特定类的文本输入中“输入”。

我的jQuery如下:

$('input.large').keypress(function (e) { if(e.which ==13) console.log("pressed enter"); }); 

我的HTML是这样的:

  Personal Name      Email    

当我给出字段ID并尝试$('#elementid').keypress有效。 但这不起作用。 我没有控制台输出。 我错过了什么?

您可以在带有keydown document使用live( .on() )事件(我认为这样更好)。 它允许您检测与选择器匹配的当前和未来元素中的keydown

HTML

 Personal Name 
Email

JS (使用jQuery 1.7+运行):

 jQuery(document).on('keydown', 'input.large', function(ev) { if(ev.which === 13) { // Will change backgroundColor to blue as example this.style.backgroundColor = '#EFF'; // Avoid form submit return false; } }); 

jsFiddle : http : //jsfiddle.net/qvhWD/

检查一下: http//jsfiddle.net/EJyyr/

使用这个HTML:

  Personal Name      Email    

这是which logs the input text id的jQuery

 $('.large').keypress(function (e) { if(e.which ==13) console.log($(this).attr('id')); }); 

感谢David Rodrigues的解释。 它帮助了很多。 我不得不升级我的JQuery库,并停止.live()函数正常工作。

您可以将它用于以下内容

单击select_all_checkboxes输入类型复选框时,选择表单的所有复选框输入:

 jQuery(document).on("click", "#select_all_checkboxes", function(){ var chk = this.checked; $('input[id=selectAll]').each(function(){ this.checked = chk; }); }); 

当用户使用tab键点击任何具有类名“email”的字段时,调用函数“checkMail”:

 jQuery(document).on("blur", 'input.email', function(event){ var email = $(this).val(); if (!checkMail(email)) { alert("Invalid email."); $(this).focus(); } });