jQuery: how to get which button was clicked upon form submission?

后端 未结 26 1367
旧巷少年郎
旧巷少年郎 2020-11-22 16:01

I have a .submit() event set up for form submission. I also have multiple forms on the page, but just one here for this example. I\'d like to know which submi

26条回答
  •  心在旅途
    2020-11-22 16:50

    Here's the approach that seems cleaner for my purposes.

    First, for any and all forms:

    $('form').click(function(event) {
      $(this).data('clicked',$(event.target))
    });
    

    When this click event is fired for a form, it simply records the originating target (available in the event object) to be accessed later. This is a pretty broad stroke, as it will fire for any click anywhere on the form. Optimization comments are welcome, but I suspect it will never cause noticeable issues.

    Then, in $('form').submit(), you can inquire what was last clicked, with something like

    if ($(this).data('clicked').is('[name=no_ajax]')) xhr.abort();
    

提交回复
热议问题