很多時候,我們為一個表單中的button寫了事件,但它不是submit,不能實現按回車鍵提交表單,那么就要為這個添加綁定事件了。
html代碼片段如下:
<tr>
<td><input type="text" name="title"></td>
<td><input type="button" name="button" class="but" id="but"></td>
</tr>
JS示例:
function BindEnter() {
if (event.keyCode == 13) {
event.cancelBubble = true;
event.returnValue = false;
document.getElementById('but').click();
}
}
咱們可以把BindEnter() 事件綁定在input上,上面的html代碼第2行改寫成:
<td><input type="text" name="title" onkeypress="BindEnter();"></td>
jQuery示例:
$(".but").click(function(){
//具體功能代碼略
})
$("input[type='text']").keypress(function(e){
if (event.keyCode == 13) {
event.cancelBubble = true;
event.returnValue = false;
$(this).parents("tr").find(".but").click();
}
})
使用class來標識按鈕,這樣具有更強的兼容性,比如有很多行類似的<tr>的數據時,每行一個按鈕。