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

You can use the function to get the id and the value for the changed item(in my example, I've used a Select tag.

              $('select').change(
                   function() {
                        var val = this.value;
                        var id = jQuery(this).attr("id");
                        console.log("value changed" + String(val)+String(id));
                   }
               );
查看更多
若你有天会懂
3楼-- · 2018-12-31 02:09

For all events, not limited to just jQuery you can use

var target = event.target || event.srcElement;
var id = target.id

Where event.target fails it falls back on event.srcElement for IE. To clarify the above code does not require jQuery but also works with jQuery.

查看更多
泪湿衣
4楼-- · 2018-12-31 02:09

This works on a higher z-index than the event parameter mentioned in above answers:

$("#mydiv li").click(function(){

    ClickedElement = this.id;
    alert(ClickedElement);
});

This way you will always get the id of the (in this example li) element. Also when clicked on a child element of the parent..

查看更多
只靠听说
5楼-- · 2018-12-31 02:09

Both of these work,

jQuery(this).attr("id");

and

alert(this.id);
查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 02:17

For reference, try this! It works!

jQuery("classNameofDiv").click(function() {
    var contentPanelId = jQuery(this).attr("id");
    alert(contentPanelId);
});
查看更多
伤终究还是伤i
7楼-- · 2018-12-31 02:18
var buttons = document.getElementsByTagName('button');
var buttonsLength = buttons.length;
for (var i = 0; i < buttonsLength; i++){
    buttons[i].addEventListener('click', clickResponse, false);
};
function clickResponse(){
    // do something based on button selection here...
    alert(this.id);
}

Working JSFiddle here.

查看更多
登录 后发表回答