this is undefined in addEventListener Callback

0

Hello, I have the following html code:

<nav id="myNav" class="nav has-shadow">
    <div class="nav-center">
        <a class="nav-item is-tab is-active">Ingresos</a>
        <a class="nav-item"><h1 id="myTitle" class="title">Letor</h1></a>
        <a class="nav-item is-tab">Gastos</a>
    </div>
</nav>

and the next js:

function startMenu(){
    let menuButtons = document.getElementsByClassName('is-tab');

    for(let i=0; i<menuButtons.length;i++ )
        menuButtons[i].addEventListener('click',()=>{
            console.log(this);
        });
}

Is there a way to access this from the callback or do I necessarily have to add a parameter in the function to find the target ?

    
asked by Cristofer Fuentes 20.07.2017 в 02:46
source

2 answers

3

The problem is because you are using a función flecha ( In English arrow function ).

  

Arrow functions capture the value of this of the current context

Solution:

Use a function

Example:

function startMenu(){
    let menuButtons = document.getElementsByClassName('is-tab');

    for(let i=0; i<menuButtons.length;i++ )
        menuButtons[i].addEventListener('click',function(){
            console.log(this);
        });
}
<nav id="myNav" class="nav has-shadow" onclick="startMenu(event)">
  <div class="nav-center">
    <a class="nav-item is-tab is-active">Ingresos</a>
    <a class="nav-item">
      <h1 id="myTitle" class="title">Letor</h1>
    </a>
    <a class="nav-item is-tab">Gastos</a>
  </div>
</nav>
    
answered by 20.07.2017 в 04:02
0

It can indeed be obtained by a target

function startMenu(e){
     console.log(e.target.nodeName);

}
<nav id="myNav" class="nav has-shadow" onclick="startMenu(event)">
    <div class="nav-center">
        <a class="nav-item is-tab is-active">Ingresos</a>
        <a class="nav-item"><h1 id="myTitle" class="title">Letor</h1></a>
        <a class="nav-item is-tab">Gastos</a>
    </div>
</nav>
    
answered by 20.07.2017 в 04:02