Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

javascript - Get the element triggering an onclick event in jquery?

I have a form where i've replaced the submit button with an input (with type=button) with an onclick which calls an existing function:

<form accept-charset="UTF-8" action="/admin/message_campaigns" class="new_message_campaign" id="new_message_campaign" method="post">
  <!-- some fields -->
      <input onclick="confirmSubmit();" type="button" value="Send" />
</form>

In the confirmSubmit, i'd like to be able to dynamically get the form object (to submit it), instead of having to hardcode the form's id, or pass it as part of the call to confirmSubmit(). I'd have thought that i could do this by first getting the dom element that was clicked on, ie something like this:

var form = $(this).parents("form");

where $(this) is the object that called the function, ie the input with the onclick. This doesn't work though. I think it would work if i'd set it up with the .click(function(){ syntax. Can i get the element that called the function in a different way?

EDIT - got the answer from @claudio below, for clarity here's the complete function and call:

<form accept-charset="UTF-8" action="/admin/message_campaigns" class="new_message_campaign" id="new_message_campaign" method="post">
  <!-- some fields -->
      <input onclick="confirmSubmit($(this));" type="button" value="Send" />
</form>

and the function itself. Note that 'jConfirm' is a method of the jquery-alerts plugin (http://abeautifulsite.net/blog/2008/12/jquery-alert-dialogs/) but that's not really relevant to this question - the key thing was just to get the form object, not what's subsequently done with it:

function confirmSubmit(caller) {
  var form = caller.parents("form");
  jConfirm('Are you sure?', 'Please Confirm', function(result){
    if (result) {
      form.submit();
    } else {
      return false;
    }
  });
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can pass the inline handler the this keyword, obtaining the element which fired the event.

like,

onclick="confirmSubmit(this);"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...