简体   繁体   English

Jquery在具有相同id的多个输入中检测按键

[英]Jquery detect keypress in multiple inputs with same id

So I have a bunch of input boxes with the same id but different names like so: 所以我有一堆输入框具有相同的ID但不同的名称如下:

<input type="text" id="description" name="1">
<input type="text" id="description" name="2">
<input type="text" id="description" name="3">

Now for a single input box (only one box uses the id) I use: 现在对于一个输入框(只有一个框使用id),我使用:

$('#description').keypress(function(....

What I would ideally like to be able to do is use the above function and then do something based on the name of the input box but for multiple input boxes to carry the same id. 我理想的是能够做的是使用上面的函数,然后根据输入框的名称做一些事情,但是多个输入框带有相同的id。 Is this possible in some way? 这有可能吗?

You should have unique id for html elements you should assign a common class and access throug it. 你应该拥有html元素的唯一id,你应该分配一个公共类并通过它访问它。

Live Demo 现场演示

<input type="text" id="description1" name="1" class="commonclass">
<input type="text" id="description2" name="2" class="commonclass">
<input type="text" id="description3" name="3" class="commonclass">


 $('.commonclass').keypress(function(event){
       alert("keycode: " + event.keyCode);
       alert("id: " + this.id);
 });​

Apply class name to multiple elements. 将类名应用于多个元素。 Then use jquery with class to handle keypress event. 然后在类中使用jquery来处理keypress事件。

It is a little bit late for my answer, but in case someone else stumbles upon this question here. 我的答案有点晚了,但万一其他人在这里偶然发现了这个问题。

For me the problem was solved by wrapping the code in the document ready event. 对我来说,问题是通过将代码包装在文档就绪事件中解决的。 This ensures the input controls exist in the DOM at the time the events are attached. 这可确保在附加事件时DOM中存在输入控件。

$(document).ready(function() {
  $('.commonclass').keypress(function(event){
    alert("keycode: " + event.keyCode);
    alert("id: " + this.id);
  });​
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM