我有两个按钮的页面。一个是<按钮> 元素,另一个是< 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.
更多推荐
输入触发器按钮单击
发布评论