[英]JS Trigger submit event while preventing default
I have a from I added a event listener to for the submit event like this: 我从中添加了一个事件侦听器,用于提交事件,如下所示:
form.addEventListener('submit',function(event){
event.preventDefault();
/*some few hundred more lines*/
},false);
My issue is when I use this bit of js later on: 我的问题是稍后在以下位置使用这部分js:
from.dispatchEvent(new Event('submit'));
The function is processed, but the page is reloaded because preventDefault()
had no effect, how can a dispatch a event and not trigger the default? 该函数已处理,但是由于preventDefault()
无效,因此重新加载了页面,如何调度事件而不触发默认值?
1) you also need e.stopPropogation(), and even though it's redundant these days, to cope with old IE, it's good form to return 0 at the end 1)您还需要e.stopPropogation(),尽管这些天已经很多余了,但要处理旧的IE,最好还是在最后返回0
2) practically speaking, just stop making the button a submit button. 2)实际上,只需停止将按钮变为提交按钮即可。 submit explicitly means "send to the other end." 明确提交是指“发送到另一端”。 just handle the button's onclick instead. 只需处理按钮的onclick即可。
Setting the action
on the form to javascript:void(0);
将表单上的action
设置为javascript:void(0);
instead of #
worked. 而不是#
有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.