Getting the ID of the element that fired an event

2018-12-31 01:38发布

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

I'm thinking something like:

<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>

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.

19条回答
长期被迫恋爱
2楼-- · 2018-12-31 02:30

You can use (this) to reference the object that fired the function.

'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.

Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/

查看更多
浅入江南
3楼-- · 2018-12-31 02:31

You can try to use:

$('*').live('click', function() {
 console.log(this.id);
 return false;
});
查看更多
人间绝色
4楼-- · 2018-12-31 02:31

I'm working with

jQuery Autocomplete

I tried looking for an event as described above, but when the request function fires it doesn't seem to be available. I used this.element.attr("id") to get the element's ID instead, and it seems to work fine.

查看更多
伤终究还是伤i
5楼-- · 2018-12-31 02:33

this works with most types of elements:

$('selector').on('click',function(e){
    log(event.currentTarget.id);
    });
查看更多
无与为乐者.
6楼-- · 2018-12-31 02:34

The source element as a jQuery object should be obtained via

var $el = $(event.target);

This gets you the source of the click, rather than the element that the click function was assigned too. Can be useful when the click event is on a parent object EG.a click event on a table row, and you need the cell that was clicked

$("tr").click(function(event){
    var $td = $(event.target);
});
查看更多
墨雨无痕
7楼-- · 2018-12-31 02:34

Use can Use .on event

  $("table").on("tr", "click", function() {
                    var id=$(this).attr('id');
                    alert("ID:"+id);  
                });
查看更多
登录 后发表回答