javascript cant get index number of data-index

Viewed 331

When I console.log(currentIndex), there just comes NaN. What should I do? I can't get any fixes about data-index. Can I even use data-index for this?

$(".element").mouseover(()=> {
  var currentIndex = parseInt($(this).data('index'));
  console.log(currentIndex);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<i class="element" data-index="0">0</i>
<i class="element" data-index="1">1</i>
<i class="element" data-index="2">2</i>
<i class="element" data-index="3">3</i>
<i class="element" data-index="4">4</i>

2 Answers

This isn't what you expect.

When you use a fat arrow function () => {} you say that 'this' shouldn't switch into your local context. By using a classic function style, you set this to the expected element and it works.

$(".element").mouseover(function()  {

  var currentIndex = parseInt($(this).data('index'));
  console.log(currentIndex);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<i class="element" data-index="0">0</i>
<i class="element" data-index="1">1</i>
<i class="element" data-index="2">2</i>
<i class="element" data-index="3">3</i>
<i class="element" data-index="4">4</i>

$(".element").mouseover((e) => {

  var currentIndex = parseInt($(e.target).data('index'));
  console.log(currentIndex);

});
Related