通过内联 JavaScript 提交表单时使用提交事件侦听器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16768433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:55:11  来源:igfitidea点击:

Use submit event listener when form is submitted via inline JavaScript?

javascriptjavascript-events

提问by user1767586

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/

它忽略事件侦听器。这是一个 JSFiddle 来演示: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.

编辑:我们无法更改标记,因为它位于我们客户的主页上,他们嵌入了我们的脚本。对不起,如果我没有说清楚。

回答by veelen

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');

});

回答by ianace

instead of using the href try this

而不是使用 href 试试这个

<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 hrefand replace it with onclick

删除href并替换为onclick

回答by Ted

try the following with jquery:

使用 jquery 尝试以下操作:

$("form").submit(function (e) {
      e.preventDefault();

      alert('event');
});

Reference here.

参考这里