使用Submit的addEventListener不起作用 [英] addEventListener using submit is not working
问题描述
当我使用'click'事件时,我的代码有效,并且它阻止了表单的提交.但是,当我使用此代码时,它不会.为什么?
When I use the 'click' event, my code works and it prevents the form from submitting. However, when I use this code it does not. Why?
submitMessage.addEventListener('submit', sendMessage, false);
function sendMessage(event){
event.preventDefault();
console.log('made it');
}
推荐答案
当我使用'click'事件时,我的代码有效,并且它阻止了表单的提交.但是,当我使用此代码时,它不会.为什么?
When I use the 'click' event, my code works and it prevents the form from submitting. However, when I use this code it does not. Why?
submit
事件仅在< form>
元素上触发.
The submit
event is only triggered on the <form>
element.
因为您说它适用于 click
,所以我假设您没有将处理程序绑定到< form>
元素.
Since you say it works for click
, I assume you are not binding the handler to the <form>
element.
从 MDN文档:
提交表单时会触发Submit事件.
The submit event is fired when a form is submitted.
Note that submit is fired only on the form element, not the button or submit input. (Forms are submitted, not buttons.)
这篇关于使用Submit的addEventListener不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!