问题
We have a script that tracks form submits by adding an event listener to the form. The problem is that one customer submits the form via a link using
<a href="javascript:document.formname.submit();">Submit</a>
which ignores the event listener. Here's a JSFiddle to demonstrate: http://jsfiddle.net/XhLkG/
As you can see the Submit button triggers the alert while the Submit link simply just submits the form and bypasses the event listener.
Is there a way to still trigger the event listener?
EDIT: We cannot change the markup since it's on our customer's homepage where they have embedded our script. Sorry if I didn't make it clear.
回答1:
You can use this:
var form = document.getElementsByClassName('form');
form[0].addEventListener("submit", function(e) {
e.preventDefault();
alert('event');
});
form[0].childNodes[3].addEventListener("click", function(e) {
e.preventDefault();
alert('event');
});
回答2:
try the following with jquery:
$("form").submit(function (e) {
e.preventDefault();
alert('event');
});
Reference here.
回答3:
instead of using the href try this
<form method="post" name="formname" class="form">
<input type="text" name="hello">
<a onclick="javascript:document.formname.submit();">Submit</a>
<input type="submit">
</form>
remove the href
and replace it with onclick
来源:https://stackoverflow.com/questions/16768433/use-submit-event-listener-when-form-is-submitted-via-inline-javascript