2013-01-21 102 views
2

我有一個帶有幾個輸入框和相應的輸入按鈕的HTML表單。當我在第一個輸入框中鍵入內容並按輸入或按鈕時,它工作正常。但是,如果我按下在其他框中輸入,就好像它在第一個框中一樣。按鈕工作正常。用多個輸入框按'輸入'

這裏是我的代碼:

<script type="text/javascript"> 
    function fn (num) { 
    alert(num); 
    document.getElementById(num).focus(); 
    } 
</script> 
</head> 
<body> 
<form> 
    <input id="1" type="text"></input> <button onclick="fn(1);">press</button><br/> 
    <input id="2" type="text"></input> <button onclick="fn(2);">press</button><br/> 
    <input id="3" type="text"></input> <button onclick="fn(3);">press</button><br/> 
</form> 

顯然,這是在ECMA一個 '夸克'(I已經在FF18.0.1和Safari 5.1.7測試)。 有沒有解決這個問題?

我發現的一個解決方案是爲每個輸入框添加一個表單。

<form> 
    <input id="1" type="text"></input> <button onclick="fn(1);">press</button><br/> 
</form> 
<form> 
    <input id="2" type="text"></input> <button onclick="fn(2);">press</button><br/> 
</form> 
<form> 
    <input id="3" type="text"></input> <button onclick="fn(3);">press</button><br/> 
</form> 

這是一個錯誤?有更好的解決方案嗎? 感謝您的任何建議。

+1

這是一個功能。或者稱之爲設計缺陷;不是一個錯誤。按鈕不與輸入框「對應」。因此,每個窗體只能有一個按鈕,以響應Enter鍵。無論你使用什麼文本框,所以你已經得到了答案,我不相信有更好的答案。 –

+2

不,問題不在於按鈕,而在於輸入框,所以你的回答完全沒有理解這一點。如果我將注意力集中在輸入框上並按下回車鍵,它應該對該輸入框進行一些操作,而不是針對其他輸入框。謝謝,但不是謝謝。 – Leo

回答

0

試試這個:

$("id").keypress(function(e) { 
    if(e.which == 13) { 
     respective functions 
    } 
}); 

<input type="text" name="q" id="q" 
     onkeypress="if (event.keyCode == 13) {call function}" /> 
2

你要改用的onClick的onkeypress事件。試試這個:

function myKeyPress(args) { 
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { 
    // do something here (enter has been pressed) 
    } 
    else { 
    return false; // somehow prevents "default" form behaviors 
    } 
}