简体   繁体   English

如何拦截onclick事件

[英]How to intercept the onclick event

I'd like to intercept the onclick event of a button (not submit) before the page posts back from the onclick. 我想在页面从onclick发回来之前拦截按钮的onclick事件(不提交)。

I'm having some trouble: 我遇到了一些麻烦:

$(document).ready() { function() {
    function validate() { 
        ...
    }

    var oldOnClick = $("input[value=OK]").attr("onclick");
    $("input[value=OK]").attr("onclick", "if(!validate()) { return false; }" + oldOnClick));
});

If you still want to handle the button click event instead of the form submit event as all suggested, you could do something like this, using an anonymous function, to call your oldOnClick function, preserving the context and the event argument: 如果您仍然希望处理按钮单击事件而不是所有建议的表单提交事件,您可以使用匿名函数执行此类操作,以调用oldOnClick函数,保留上下文和事件参数:

$(document).ready(function () {
  function validate() { 
    // ...
  }

  var oldOnClick = $("input[value=OK]").get(0).onclick;
  $("input[value=OK]").click(function (e) {
    if(!validate()) {
      return false;
    }
    oldOnClick.call(this, e); // enforce the context and event argument
  });
});

Rather than trying to intercept the onClick event, you should use the submit event . 您应该使用submit事件 ,而不是尝试拦截onClick 事件

Why? 为什么? Simple, not all forms are submitted by clicking, what about tab, enter, etc? 很简单,并非所有表单都是通过点击,标签,输入等提交的?

$("form").submit(function() { // do validation/stuff here }); will do the trick. 会做的。

You can return false; 你可以return false; to stop the form submitting, or return true; 停止提交表单,或return true; if you want to let it through. 如果你想让它通过。 Do your validation within the .submit itself. .submit本身内进行验证。

OnSubmit is called just before the form is submit. 在提交表单之前调用OnSubmit。 You can even cancel the event, so the form isn't submitted. 您甚至可以取消该活动,因此不会提交表单。

e.preventDefault();

More specifically you need to do this 更具体地说,你需要这样做

$("#Your_form_id").submit(function(e) {
e.preventDefault();
// your code
});

The other way to do this, is as Jake says, return false after doing some work ... ie: 另一种方法是,杰克说,做完一些工作后返回假...即:

$("#Your_form_id").submit(function() {
// your code
return false;
});

See the Jquery documentation on Submit and Events in general 有关提交事件的一般信息,请参阅Jquery文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM