submit eventListener和submit method的区别

这个问题曾经让我头痛了一段时间,今天看到greasemonkey的文档,把这个问题说的很清楚,而且给了解决方法,留在这里做个备份

Example: Do something before a form is submitted
function newsubmit(event) {
var target = event ? event.target : this;
// do anything you like here
alert('Submitting form to ' + target.action);
// call real submit function
this._submit();
}
// capture the onsubmit event on all forms
window.addEventListener('submit', newsubmit, true);
// If a script calls someForm.submit(), the onsubmit event does not fire,
// so we need to redefine the submit method of the HTMLFormElement class.
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = newsubmit;
There are two things going on here. First, I am adding an event listener that traps submit events. A submit event
occurs when the user clicks a Submit button on a form. However, if another script manually calls the submit()
method of a form, the submit event does not fire. So, the second thing I do is override the submit method of the
HTMLFormElement class.
But wait, there's more. Both the event listener and the method override point to the same function, newsubmit. If
newsubmit gets called via a submit event, the event argument will be populated with an event object that
contains information about the event (for example, event.target will be the form being submitted). However, if a
script manually calls the submit method, the event argument will be missing, but the global variable this will
point to the form. Therefore, in my newsubmit function, I test whether event is null, and if so, get the target form
from this instead.
Tip:
A submit event fires when a user submits a form in the usual way, i.e. by clicking the form's Submit
button or hittingENTER within a form. However, the submit event does not fire when the form is
submitted via a script calling aForm.submit(). Therefore you need to do two things to capture a
form submission: add an event listener to capture to submit event, and modify the prototype of the
HTMLFormElement class to redirect the submit() method to your custom function.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值