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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16091823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:24:52  来源:igfitidea点击:

Get clicked element using jQuery on event?

jqueryevent-handlingclickjquery-events

提问by Devil's Advocate

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?

通常,如果您只是这样做,$('.appDetails').click()您可以使用它$(this)来获取被点击的元素。我将如何使用上述代码完成此操作?

For instance:

例如:

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

回答by bipen

As simple as it can be

尽可能简单

Use $(this)here too

也用$(this)在这里

$(document).on("click",".appDetails", function () {
   var clickedBtnID = $(this).attr('id'); // or var clickedBtnID = this.id
   alert('you clicked on button #' + clickedBtnID);
});

回答by Bastian Rang

You are missing the event parameter on your function.

您的函数中缺少 event 参数。

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

回答by waffleau

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

处理此问题的传统方式在 ES6 中表现不佳。你可以这样做:

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

回答by Emmanuel Nwaduba

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

一种简单的方法是将 data 属性传递给您的 HTML 标记。

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>