获取元素在jquery中触发onclick事件? [英] Get the element triggering an onclick event in jquery?

查看:176
本文介绍了获取元素在jquery中触发onclick事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,我用一个带有onclick的输入(带有type =按钮)替换了提交按钮,该onclick调用现有函数:

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>

在confirmSubmit中,我希望能够动态获取表单对象(提交它) ),而不是硬编码表单的id,或作为调用confirmSubmit()的一部分传递它。我原本以为我可以通过首先获得点击的dom元素来做到这一点,例如:

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");

其中$(this)是调用函数的对象,即带onclick的输入。但这不起作用。如果我用 .click(function(){语法设置它,我认为工作。我可以获得调用的元素吗?功能以不同的方式?

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?

编辑 - 从下面的@claudio得到答案,为清楚起见这里是完整的功能和电话:

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>

和函数本身。请注意'jConfirm'是一种方法jquery-alerts插件(http://abeautifulsite.net/blog/2008/12/jquery-alert-dialogs/),但这与这个问题并不真正相关 - 关键是获取表单对象,而不是什么随后用它完成:

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;
    }
  });
}


推荐答案

您可以传递内联处理程序这个关键字,获取触发事件的元素。

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

喜欢,

onclick="confirmSubmit(this);"

这篇关于获取元素在jquery中触发onclick事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆