在事件上使用 jQuery 获取单击的元素?

我使用以下代码来检测动态生成的按钮何时被单击。

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

通常情况下,如果您只是执行 $('.appDetails').click(),那么您可以使用 $(this)来获取被单击的元素。如何使用上面的代码来实现这一点?

例如:

$(document).on("click",".appDetails", function () {
var clickedBtnID = ??????
alert('you clicked on button #' + clickedBtnID);
});
241858 次浏览

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

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
alert(event.target.id);
});

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

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>

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;
});
$(".masonry__img").click((e) => {
console.log(e.currentTarget.currentSrc);
});

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