防止焦点集中在纯 JavaScript 中的按钮单击上

发布于 2024-12-09 01:28:22 字数 266 浏览 1 评论 0原文

我或多或少面临着此处描述的相同问题,(即我有一个提交输入在选项卡后获得焦点时以编程方式单击,但当用户单击按钮时也会调用焦点处理程序,从而导致双重提交)。链接帖子中建议的解决方案有效,但我需要一个不需要 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我是男神闪亮亮 2024-12-16 01:28:22

您需要阻止表单提交,因此添加一个事件侦听器,然后编写您希望 JavaScript 如何处理提交表单的代码。另外,对于您询问如何在不依赖任何框架的情况下胜任编码的问题也+1! :-)

一些粗略的代码可以让您了解如何阻止表单提交...

if (window.addEventListener)
{
 forms[i].addEventListener('submit',function(e) {e.preventDefault(); eval(id_forms[e.target.id]+'();');},false);
}
else if (window.attachEvent)
{
 forms[i].attachEvent('onsubmit',function(e,f) {e.returnValue=false; eval(id_forms[e.srcElement.id]+'();');});
}

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...

if (window.addEventListener)
{
 forms[i].addEventListener('submit',function(e) {e.preventDefault(); eval(id_forms[e.target.id]+'();');},false);
}
else if (window.attachEvent)
{
 forms[i].attachEvent('onsubmit',function(e,f) {e.returnValue=false; eval(id_forms[e.srcElement.id]+'();');});
}
一杆小烟枪 2024-12-16 01:28:22

我最终得到了一个 keyUp 和 keyDown 处理程序,在其中设置/取消设置 isKeyPressed 变量。据我了解,按 Tab 键时发生的事件顺序如下:

  • keyDown
  • 获得焦点
  • keyUp

因此,在焦点事件处理程序中,我检查是否通过 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:

  • keyDown
  • focus gained
  • keyUp

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文