button绑定回车事件

很多时候,我们为一个表单中的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>的数据时,每行一个按钮。

  

原文地址:https://www.cnblogs.com/romanticcrystal/p/13897517.html