提交表单的事件监听器 [英] Submit Event Listener for a form

查看:71
本文介绍了提交表单的事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为表单提交编写了一个事件监听器,这引起了一些问题。在文本字段内按输入时一切正常。但是,我有一个span(带有background-image),通过click事件提交表单。这不能正常工作,我无法弄清楚原因。

I've written an event listener for a form submit that is causing me a few issues. When pressing 'enter' inside the text field everything works fine. However, I have an span (with background-image) that submits the form as well via a click event. This is not working properly and I can't figure out why.

这是基本的HTML:

<form name="myForm">
  <input type="text" name="search" />
  <span id="search-button"></span>
</form>

这是事件监听器的JS:

Here's the JS for the event listener:

function evtSubmit(e) {
  // code
  e.preventDefault();
};

var myform = document.myForm;
if (myform.addEventListener) {
  myform.addEventListener('submit', evtSubmit, false);
}

这里是'span'及其点击事件的JS:

And here's the JS for the 'span' and its click event:

var searchButton = document.getElementById('search-button');
if (searchButton) {
 searchButton.onclick = function() {
  document.myForm.submit();
 };
}

注意:span的click事件的JS位于单独的JS文件中无法访问的atm,因此更改该脚本不是一个选项。如果解决这个问题的唯一方法是更新该文件,我可以...但由于我无法控制的进程,这要困难得多。

NOTE: The JS for the span's click event is in a separate JS file and inaccessible atm, so changing that script is less of an option. If the only way to fix this issue is to update that file, I can...but due to processes beyond my control, it's much more difficult.

推荐答案

调用 form.submit()时,不会触发 onsubmit 事件。作为替代方案,您可以将action属性设置为 javascript:evtSubmit(event)

When calling form.submit(), the onsubmit event won't be triggered. As an alternative, you can set the action attribute to javascript:evtSubmit(event):

function evtSubmit(e) {
  // code
  e.preventDefault();
};

var myform = document.myForm;
myform.setAttribute('action', 'javascript:evtSubmit();');

这篇关于提交表单的事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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