Why does the onclick function not work on a hyperlink?

2

Hello, I'm new to programming and I'm trying to create an icon that when you click on it the information will be saved through a sessionStorage, and at the same time it will be redirected to another page where I'll fill it out with information from sessionStorage. I'm using this div:

<a href="icone.html" onclick=pegarInfo()>

Could someone explain to me why it does not work? and how can I get around this?

    
asked by anonymous 23.07.2018 / 23:17

1 answer

3

Considering the comments of @Guilherme Nascimento:

  

it works intermittently or it oscillates is not working, the moment that redirect of page, even if some script is in execution something will be destroyed, it may or may not fail, it does not make sense and it should not be done, things have to be planned to work and not for "maybe it works" or "think it works". Simply href="icone.html" will redirect and at this point any attempt to run script on a page that is unloading to load another will be a factor of "competition" there are no guarantees.

I suggest you remove the href and put window.location in the getInfo () function

Why use either a onclick or another href ?

Imagine a competition scenario

function pegarInfo(){
  setTimeout(function(){
      alert("isso deve executar dentro de 2 segundos");
  }, 2000);
}
<a href="icone.html" onclick="pegarInfo()">Teste</a>

function pegarInfo(){
  setTimeout(function(){
      alert("isso deve executar dentro de 2 segundos");
      window.location = "icone.html";
  }, 2000);
}
<a onclick="pegarInfo()">Teste</a>
    
23.07.2018 / 23:56