验证后禁用/启用 onClick 事件

Disable/Enable onClick Event after Validation?

本文关键字:启用 onClick 事件 验证      更新时间:2023-09-26

我正在使用 Jquery 验证 1.9.0 插件在提交表单之前对其进行验证。

http://jqueryvalidation.org/

我在表单提交按钮上的 onClick 属性中有 Google 事件跟踪代码,在表单验证完成并且表单实际提交之前,我不想触发该代码,以便提高 Google 跟踪数据的准确性。

<button class="btn btn-primary" type="submit" onClick="ga('send', 'event', 'Form Submit', 'Button Click', 'A visitor has filled out the form.');">Submit</button>
什么是

防止 onClick 属性中的函数触发的干净方法,表单验证完成后,表单将提交,但在提交之前,表单应触发ga事件跟踪代码。

使用 $.validate 调用的 submitHandler 选项。 它仅在表单有效时触发:

$(form).validate({
   //your usual stuff here
   submitHandler: function(){
     ga('send', 'event', 'Form Submit', 'Button Click', 'A visitor has filled out the form.');
   }
});

验证表单后,您应该在表单提交事件上触发分析事件:

在表单上添加一个提交事件:

<form onsubmit="submitMyForm(this);return false;">...</form>

最好是先用一种方法来做到这一点。 Id 在提交表单时有一个功能,如下所示:

funtion submitMyForm(form)
{
    if ($(form).valid())
    {
       ga('send', 'event', 'Form Submit', 'Button Click', 'A visitor has filled out the form.');
      $(form).submit();
    }
}