在document.on函数中获取事件的当前目标

时间:2018-12-04 09:04:46

标签: javascript jquery ajax event-handling

我目前面临以下问题。在我的网站上,用户可以删除自己的条目。按下删除按钮后,将进行Ajax调用。交付了新内容,并且容器中填充了新条目。 我首先清空容器,然后用新的内容填充它。当我清空容器时,我会丢失一个条目内所有按钮上的所有事件。要解决此问题,我使用以下代码

$(document).on('click', '.DeleteButton', function (event: Event) { ... });

现在我面临的问题是,当我访问事件的当前目标时,它将为我提供整个文档。我需要currenttarget首先知道按下了哪个按钮,然后在按钮中获取ID。

我将不胜感激!

3 个答案:

答案 0 :(得分:1)

在该事件处理程序回调中,this将引用被单击的.DeleteButton元素。

$(document).on('click', '.DeleteButton', function (event: Event) {
    // Use `this` here, for instance `this.id` to get the ID of the `.DeleteButton`
});

实时示例:

$(document).on('click', '.DeleteButton', function (event/*: Event*/) {
    console.log("Clicked:", this.id);
});
<div>
  <input type="button" id="btn1" class="DeleteButton" value="One">
  <input type="button" id="btn2" class="DeleteButton" value="Two">
  <input type="button" id="btn3" class="DeleteButton" value="Three">
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

找到了解决方案。有趣的是,this无效。现在,我的代码看起来像这样。

$(document).on("click", '.DeleteButton', DeleteButtonHandler.bind(this));

我没有把这个代码片段放在我这愚蠢的问题中。在我看来this在这里不起作用。但是我找到了解决方案。我现在使用event.currentTarget而不是使用event.target。这为我提供了包含数据的正确按钮。我什至不知道为什么。如果有人对此有任何解释,请向我解释。

相关问题