提交表单的事件监听器
我为表单提交编写了一个事件侦听器,这导致了我一些问题。当在文本字段内按“输入”时,一切正常。但是,我有一个跨度(带有背景图像)也通过单击事件提交表单。这不能正常工作,我不明白为什么。
这是基本的 HTML:
<form name="myForm">
<input type="text" name="search" />
<span id="search-button"></span>
</form>
这是事件侦听器的 JS:
function evtSubmit(e) {
// code
e.preventDefault();
};
var myform = document.myForm;
if (myform.addEventListener) {
myform.addEventListener('submit', evtSubmit, false);
}
这是“span”及其单击事件的 JS:
var searchButton = document.getElementById('search-button');
if (searchButton) {
searchButton.onclick = function() {
document.myForm.submit();
};
}
注意:span 的单击事件的 JS 位于单独的 JS 文件中,目前无法访问,因此需要更改该脚本不是一个选择。如果解决此问题的唯一方法是更新该文件,我可以...但由于流程超出我的控制范围,这要困难得多。
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:
<form name="myForm">
<input type="text" name="search" />
<span id="search-button"></span>
</form>
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);
}
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();
};
}
NOTE: The JS for the span's click event is in a separate JS file and inaccessible at the moment, 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
调用
form.submit()
时,不会触发onsubmit
事件。作为替代方案,您可以将操作属性设置为javascript:evtSubmit(event)
:When calling
form.submit()
, theonsubmit
event won't be triggered. As an alternative, you can set the action attribute tojavascript:evtSubmit(event)
: