输入触发器按钮单击 [英] Enter triggers button click

查看:129
本文介绍了输入触发器按钮单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个按钮的页面。一个是<按钮> 元素,另一个是< input type =submit> 。这些按钮按照该顺序出现在页面上。如果我在表单中的任何位置的文本字段中,并按< Enter> ,则按钮元素的点击事件被触发。我认为这是因为按钮元素第一。

I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

我找不到任何看起来像设置默认按钮的可靠方式,也不一定要在这点。在没有任何更好的情况下,我在窗体上的任何位置捕获了一个按键,如果它是按下的< Enter> 键,我只是否定它:

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false; 
  }
})

据我目前的情况看来,这似乎是有效的,但感觉令人难以置信的火腿-fisted。有没有人知道这样做的更复杂的技术?同样,这种解决方案有什么缺陷,我只是不知道?

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted. Does anyone know of a more sophisticated technique for doing this? Similarly, are there any pitfalls to this solution that I'm just not aware of?

谢谢。

推荐答案

使用

Using

<button type="button">Whatever</button>

应该这样做。

原因是因为表单中的按钮将其类型隐式设置为 submit 。正如zzzzBoz所说,Spec说第一个按钮输入并且 type =submit 是在这种情况下触发的。如果您特别设置了 type =button,那么浏览器将不会考虑它。

The reason is because a button inside a form has its type implicitly set to submit. As zzzzBoz says, the Spec says that the first button or input with type="submit" is what is triggered in this situation. If you specifically set type="button", then it's removed from consideration by the browser.

这篇关于输入触发器按钮单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆