1

所以我有一堆具有相同 id 但名称不同的输入框,如下所示:

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

现在对于单个输入框(只有一个框使用 id),我使用:

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

我希望能够做的是使用上面的函数,然后根据输入框的名称做一些事情,但让多个输入框携带相同的 id。这在某种程度上可能吗?

4

3 回答 3

5

您应该有 html 元素的唯一 ID,您应该分配一个公共类并通过它访问。

现场演示

<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);
 });​
于 2012-11-19T04:54:32.973 回答
0

将类名应用于多个元素。然后使用带有类的jquery来处理按键事件。

于 2013-08-29T07:31:23.477 回答
0

我的回答有点晚了,但万一其他人在这里偶然发现了这个问题。

对我来说,问题是通过将代码包装在文档就绪事件中来解决的。这可确保在附加事件时输入控件存在于 DOM 中。

$(document).ready(function() {
  $('.commonclass').keypress(function(event){
    alert("keycode: " + event.keyCode);
    alert("id: " + this.id);
  });​
});
于 2016-02-15T08:30:20.583 回答