简体   繁体   English

提交表单的事件监听器

[英]Submit Event Listener for a form

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. 但是,我有一个跨度(带有背景图像),它也可以通过click事件提交表单。 This is not working properly and I can't figure out why. 这不能正常工作,我不知道为什么。

Here's the basic HTML: 这是基本的HTML:

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

Here's the JS for the event listener: 这是事件监听器的JS:

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

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

And here's the JS for the 'span' and its click event: 这是“ span”及其点击事件的JS:

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

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. 注意:用于span的click事件的JS位于单独的JS文件中,并且无法访问atm,因此更改该脚本的选择较少。 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. 如果解决此问题的唯一方法是更新该文件,则可以...但是由于无法控制的过程,要困难得多。

When calling form.submit() , the onsubmit event won't be triggered. 调用form.submit() ,不会触发onsubmit事件。 As an alternative, you can set the action attribute to javascript:evtSubmit(event) : 或者,您可以将action属性设置为javascript:evtSubmit(event)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM