Get clicked element using jQuery on event?

后端 未结 4 2128
深忆病人
深忆病人 2020-11-28 04:49

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

$(document).on(\"click\",\".appDetails\", function () {
    alert(\"t         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 05:47

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

提交回复
热议问题