输入触发器按钮单击

编程入门 行业动态 更新时间:2024-10-27 20:36:33
本文介绍了输入触发器按钮单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个按钮的页面。一个是<按钮> 元素,另一个是< 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.

更多推荐

输入触发器按钮单击

本文发布于:2023-11-12 04:56:10,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:触发器   单击   按钮

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!