The difference and usage of js onclick and addEventListener

addEventListener (recommended) is like a listener container, which can hold many listener events, and each event will be executed.

onclick Before today, I used this (onclick) more (simply because I saw it basically used this, a disadvantage is that the same element is bound to two different events, the previous event will be overwritten by the next event.

I asked about the difference between the two in the company today, and I was very impressed. I also verified it myself. Here is the last paragraph of my verification code (the '222' in the code will be overwritten and will not pop up), you can also try it:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>onclick and addEventListener</title>
        <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
    </head>
    <body>
        <div id="btnOk1">111</div>
        <script>
            document.getElementById('btnOk1').addEventListener('click',function(){
                alert('111');
            });
            document.getElementById('btnOk1').addEventListener('click',function(){
                alert('333');
            });
            document.getElementById('btnOk1').onclick = function(){
                alert('222');
            }
            document.getElementById('btnOk1').onclick = function(){
                alert('444');
            }
        </script>
    </body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324613351&siteId=291194637