2012-11-19 58 views
1

所以我有一大堆的輸入框具有相同的ID,但不同的名稱,像這樣:jQuery的檢測按鍵在多個輸入與同一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。這在某種程度上可能嗎?

+5

的ID必須是唯一的 – Fee

+0

請避免多個輸入ID相同的ID是標識作出這樣的出現在你的頁面只有一個時間,你可以使用類用於此目的 –

+0

我換了ID爲類,但仍然沒有按」 t工作 – crazymao

回答

5

您應該爲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); 
});​ 
+0

這並沒有工作,它仍然沒有檢測到與更多具有相同類的輸入框的按鍵:/ – crazymao

+0

它應該工作。也許你的處理函數沒有正確寫入(它需要使用'$(this)'引用當前的輸入框)。 – Barmar

+0

我添加了演示的鏈接 – Adil

0

應用類名的多個元素。然後使用jquery和class來處理按鍵事件。

0

對於我的回答來說有點晚,但萬一有人在這裏遇到這個問題。

對我來說,問題是通過將代碼包裝在文檔就緒事件中解決的。 這確保了在事件附加時DOM中存在輸入控件。

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