119

I'm using the following code to detect when a dynamically generated button is clicked.

$(document).on("click",".appDetails", function () {
    alert("test");
});

Normally, if you just did $('.appDetails').click() you could use $(this) to get the element that was clicked on. How would I accomplish this with the above code?

For instance:

$(document).on("click",".appDetails", function () {
    var clickedBtnID = ??????
    alert('you clicked on button #' + clickedBtnID);
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

6 Answers6

165

As simple as it can be

Use $(this) here too

$(document).on("click",".appDetails", function () {
   var clickedBtnID = $(this).attr('id'); // or var clickedBtnID = this.id
   alert('you clicked on button #' + clickedBtnID);
});
Liam
  • 27,717
  • 28
  • 128
  • 190
bipen
  • 36,319
  • 9
  • 49
  • 62
68

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});
Bastian Rang
  • 2,137
  • 1
  • 19
  • 25
  • 10
    This was perfect for me. It gives the element that was clicked - $(this) only gave the element that had the event attached. – Bill Tarbell Jul 31 '15 at 16:44
49

The conventional way of handling this doesn't play well with ES6. You can do this instead:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);

  this.delete(clickedElement.data('id'));
});

Note that the event target will be the clicked element, which may not be the element you want (it could be a child that received the event). To get the actual element:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);
  const targetElement = clickedElement.closest('.delete');

  this.delete(targetElement.data('id'));
});
waffleau
  • 1,054
  • 11
  • 6
  • 6
    You should use `event.currentTarget` to get the element the event is bound to. `event.target` is indeed the element that triggered the event. Your code `clickedElement.closest('.delete');` could fail if you have multiple nested elements with this class. – Mark Baijens Mar 16 '21 at 14:53
2

There are many ways you can do that

The first method is by using the javascript target

$(document).on("click",".appDetails", function (event) {
    var clickebtn = target.event.id;
});
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
iamnonso
  • 105
  • 1
  • 4
1
$(".masonry__img").click((e) => {
      console.log(e.currentTarget.currentSrc);
});

This will add an onClick handler to each image with the class masonry__img.

jpeggtulsa
  • 61
  • 5
0

A simple way is to pass the data attribute to your HTML tag.

Example:

<div data-id='tagid' class="clickElem"></div>

<script>
$(document).on("click",".appDetails", function () {
   var clickedBtnID = $(this).attr('data');
   alert('you clicked on button #' + clickedBtnID);
});
</script>
iamnonso
  • 105
  • 1
  • 4