防止焦点集中在纯 JavaScript 中的按钮单击上
我或多或少面临着此处描述的相同问题,(即我有一个提交输入在选项卡后获得焦点时以编程方式单击,但当用户单击按钮时也会调用焦点处理程序,从而导致双重提交)。链接帖子中建议的解决方案有效,但我需要一个不需要 jQuery 的解决方案。有人对此有什么想法吗?请注意,我需要按钮的单击行为保持不变,因为它绑定到 asp .net 服务器端事件。谢谢你!
I am facing more or less the same problem described here, (i.e. I have a submit input which is clicked programmatically when it gains focus after a tab, but the focus handler is also invoked when the user clicks on the button, causing a double submit). The solution suggested in the linked post works, but I need one which does not require jQuery. Does anyone have some thoughts on that? Please note that I need the button's click behavior to remain the same, as it is binded to an asp .net server-side event. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要阻止表单提交,因此添加一个事件侦听器,然后编写您希望 JavaScript 如何处理提交表单的代码。另外,对于您询问如何在不依赖任何框架的情况下胜任编码的问题也+1! :-)
一些粗略的代码可以让您了解如何阻止表单提交...
You'll want to prevent the form from submitting so add an event listener and then code how you want JavaScript to handle submitting the form. Also +1 to your question for asking how to competently code this without depending on any frameworks! :-)
Some rough code to give you an idea of how to prevent a form from submitting...
我最终得到了一个 keyUp 和 keyDown 处理程序,在其中设置/取消设置 isKeyPressed 变量。据我了解,按 Tab 键时发生的事件顺序如下:
因此,在焦点事件处理程序中,我检查是否通过 Tab 键获得焦点(即 isKeyPressed 是否设置为 true)并提交在那里形成。否则,如果在单击()后获得焦点,则 isKeyPressed 将不会设置为 true,并且我不会以编程方式触发表单提交。
I ended up with having a keyUp and keyDown handler in which I set/unset a isKeyPressed variable. It is my understanding that the sequence of events that happens when tabbing is the following:
Thus, in the focus event handler I check if the focus was gained by tabbing (i.e. if the isKeyPressed is set to true) and submit the form there. Otherwise, if the focus was gained after a click(), the isKeyPressed will not be set to true, and I will not trigger the form submission programatically.