Click me - button.onclick...">

Compare several ways to write js html

I have 3 lines for the same result

  • <button onclick="myFunction()">Click me</button>
  • button.onclick=function(){alert('This is my test')};
  • button.addEventListener("click", fuction(){alert('This is my test')});

Could you say the best way.

+4
source share
1 answer

I recommend method 3.

If you use the first method, one drawback is the more complex maintenance. If you want to change the name of a function, you will need to change it in several files - the cause of many errors.

Assuming you run your JavaScript after loading the DOM, I (personally) define the function, and then attach it to the button as follows:

function buttonListener(event) 
// ...
button.addEventListener('click', buttonListener);

This way your JavaScript stays in one file.

, ( DOM) <script> , .

2, - ( ).

+5

All Articles