javascript 提交表单的事件监听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3841298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submit Event Listener for a form
提问by CoryDorning
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.
我为表单提交编写了一个事件侦听器,这导致了一些问题。在文本字段内按“输入”时,一切正常。但是,我有一个跨度(带有背景图像)也通过单击事件提交表单。这不能正常工作,我不知道为什么。
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. 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.
注意:span 的点击事件的 JS 位于单独的 JS 文件中并且无法访问 atm,因此更改该脚本的可能性较小。如果解决此问题的唯一方法是更新该文件,我可以……但由于过程超出我的控制范围,这要困难得多。
回答by Lekensteyn
When calling form.submit(), the onsubmitevent won't be triggered. As an alternative, you can set the action attribute to javascript:evtSubmit(event):
调用 时form.submit(),onsubmit不会触发该事件。作为替代方案,您可以将 action 属性设置为javascript:evtSubmit(event):
function evtSubmit(e) {
// code
e.preventDefault();
};
var myform = document.myForm;
myform.setAttribute('action', 'javascript:evtSubmit();');

