获取触发事件的元素的ID [英] Getting the ID of the element that fired an event

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

问题描述

有没有办法获取触发事件的元素的ID?

Is there any way to get the ID of the element that fires an event?

我在想这样的事情:

<html>
  <head>
    <script type="text/javascript" src="starterkit/jquery.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("a").click(function () {
          var test = caller.id;
          alert(test.val());
        });
      });
    </script>
  </head>
  <body>
    <form class="item" id="aaa">
      <input class="title"></input>
    </form>
    <form class="item" id="bbb">
      <input class="title"></input>
    </form>
  </body>

</html>

当然,var test 除外包含id aaa,如果从第一个表单触发事件,则bbb,如果事件是从第二种形式触发的。

Except of course that the var test should contain the id "aaa", if the event is fired from the first form, and "bbb", if the event is fired from the second form.

推荐答案

在jQuery中 event.target 始终引用触发事件的元素,其中'event'是传递给函数的参数。 http://api.jquery.com/category/events/event-object/

In jQuery event.target always refers to the element that triggered the event, where 'event' is the parameter passed to the function. http://api.jquery.com/category/events/event-object/

$(document).ready(function() {
    $("a").click(function(event) {
        alert(event.target.id);
    });
});

另请注意'this'也将工作,但它不是一个jQuery对象,所以如果你想在它上面使用jQuery函数,那么你必须将它称为'$(this)',例如:

Note also that 'this' will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as '$(this)', e.g.:

$(document).ready(function() {
    $("a").click(function(event) {
        // this.append wouldn't work
        $(this).append(" Clicked");
    });
});

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

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