jQuery: Find clicked element when binding to a form submission event?

前端 未结 2 1397
别那么骄傲
别那么骄傲 2021-01-01 21:59

I think this should be simple. Say I\'ve got the following jQuery:

$someForm.live(\'submit\', function(event) {
// do something
});

If there

相关标签:
2条回答
  • 2021-01-01 22:35

    You can use the target property of the event object to get the element that initiated the event:

    $(":submit").click(function(event) {
        var initiatingElement = event.target;
        // Do something with `initiatingElement`...
    });
    

    EDIT: Note that, for that to work, you will have to handle the click events of your submit buttons instead of the submit event of your form.

    0 讨论(0)
  • 2021-01-01 22:44

    Normally you can use event.target for the element itself...and in this case, since it's a native DOM property, just use .name as well:

    $someForm.live('submit', function(event) {
      var name = event.target.name;
    });
    

    However, since submit doesn't originate from the button, only a click does, you want something more like this:

    $("form :submit").live('click', function(event) {
      var name = this.name;
    });
    

    Use this here, because as @patrick points out, a <button> can have children as well, and the target may be a child in those cases.

    0 讨论(0)
提交回复
热议问题