点击事件的三种绑定方式

  1. HTML中使用onclick属性
  2. JS中使用onclick属性
  3. JS中使用addEvenListener()方法

三种方法的比较

在第二、三种方法中,可以向函数传入一个event对象,并读取其相应属性,而方法一不可以。

语法细节

  • 在第一种方法中,onclick大小写无关,但在第二种方法中,必须使用小写。因为HMTL对大小写不敏感,而JS则会区分大小写。
  • 在第二、三种方法中,指定函数名时没有双引号,而第一种作为一个HTML属性,需要双引号。
  • 第一种方法调用的函数后需要括号,第二、三种不需要。

HTML中使用onclick属性

<html>
<head>
    <title>方式一</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>

JS中使用onclick属性

<html>
<head>
    <title>方式二</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中使用addEvenListener()方法

<html>
<head>
    <title>方式三</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>

猜你喜欢

转载自blog.csdn.net/bertZuo/article/details/83107459