$ (this) selects a window object instead of clicking a jquery element

I have a really weird problem. I just want to select an item with a click. I did this many times and it always worked, but this time the jQuery $ (this) selector does not select the element with a click, it selects the window object. Please let me know if you have any idea what might be causing this. I am using jQuery 2.1.4 and Twitters Bootstrap 3.3.5

HTML:

<a class="btn btn-danger btn-xs delete-file"><i class="fa fa-trash" aria-hidden="true"></i> Löschen</a>

JQuery

$(document).ready( () => {
   $('.delete-file').on('click', () => {
      let element = $(this);
      console.log(element);
    });
});

Console Out:

n.fn.init [Window]

instead:

n.fn.init [a.btn.btn-danger.btn-xs.delete-file]

Thank you in advance!

+4
source share
1 answer

This is because you are using the arrow function. The scope of this function does not change according to the standard definition of a function. For thisyou need to change the logic:

$(document).ready(() => {
  $('.delete-file').on('click', function() {
    let element = $(this);
    console.log(element);
  });
});

, , target , :

$(document).ready( () => {
  $('.delete-file').on('click', (e) => {
    let element = $(e.target);
    console.log(element);
  });
});
+10

Source: https://habr.com/ru/post/1695241/


All Articles