Good day! There was such a problem. Redirect does not work in js

<a id="aaa" onclick="href();" href="#"></a> 

Tried it in these ways, but nothing helps

 <script language="JavaScript"> function href() { window.location.replace("http://stackoverflow.com"); document.location.href='http://stackoverflow.com' } </script> 
  • why not just install href links? why javascript here? - Grundy
  • By the way, the first thing you need to look for errors in the browser console. - Grundy

1 answer 1

The problem is that inline handlers are executed in the context of the HTML element.

that is, everything that is used is first searched in the html element, and in this case href is a property of the a element, not a function.

You can check it simply by changing the code for the next

 <a id="aaa" onclick="console.log(this.href===href, href);" href="#">НаТми мСня</a> 

To fix it, just change the name of the handler function:

 <script language="JavaScript"> function func() { console.log('я дСлаю Ρ€Π΅Π΄ΠΈΡ€Π΅ΠΊΡ‚'); document.location.href = 'http://stackoverflow.com' } </script> <a id="aaa" onclick="func();" href="#">НаТми мСня</a> 

Or hang the handler using the addEventListener function

 function func() { console.log('я дСлаю Ρ€Π΅Π΄ΠΈΡ€Π΅ΠΊΡ‚'); document.location.href = 'http://stackoverflow.com' } document.getElementById('aaa').addEventListener('click', func); 
 <a id="aaa" href="#">НаТми мСня</a>