Three Binding Methods for Click Events

Keywords: Web Development Attribute

  1. Using onclick attributes in HTML
  2. Using onclick attributes in JS
  3. JS uses the addEvenListener() method

Comparison of three methods

In the second and third methods, an event object can be passed into the function and its corresponding attributes can be read, but none of the methods can.

Grammatical details

  • In the first method, onclick is case-independent, but in the second method, lowercase must be used. Because HMTL is not case sensitive, while JS is case sensitive.
  • In the second and third methods, there are no double quotes when specifying the function name, while the first one, as an HTML attribute, requires double quotes.
  • The first method calls functions that need parentheses, and the second and third methods do not.

Using onclick attributes in HTML

<html>
<head>
    <title>One way</title>
    <style>
        #demo{width: 50px;height: 50px;background-color: #ccc;cursor: pointer;}
    </style>
    <script>
        function add(){
            var sum;
            sum=9+15;
            alert(sum);
        }
    </script>
</head>
<body>
    <div id="demo" onclick="add()"></div>
</body>
</html>

Using onclick attributes in JS

<html>
<head>
    <title>Mode two</title>
    <style>
        #demo{width: 50px;height: 50px;background-color: #ccc;cursor: pointer;}
    </style>
    <script>
        function add(){
            var sum;
            sum=9+15;
            alert(sum);
        }
        window.onload=function(){
            var box=document.getElementById("demo");
            box.onclick=add;
        }
    </script>
</head>
<body>
    <div id="demo"></div>
</body>
</html>

JS uses the addEvenListener() method

<html>
<head>
    <title>Mode three</title>
    <style>
        #demo{width: 50px;height: 50px;background-color: #ccc;cursor: pointer;}
    </style>
    <script>
        function add(){
            var sum;
            sum=9+15;
            alert(sum);
        }
        window.onload=function(){
            var box=document.getElementById("demo");
            box.addEventListener("click",add);
        }
    </script>
</head>
<body>
    <div id="demo"></div>
</body>
</html>

 

Posted by edup_pt on Fri, 01 Feb 2019 02:06:15 -0800