JS事件綁定的三種方式比較

js事件html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
        input{
            display: block;
            margin-bottom:10px;
        }
        .active{
            color:orange;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){

            var btn = document.querySelector("#btn");
            //時間句柄
            var clickme = function(){
                alert("hello~");
            }
            btn.addEventListener("click", clickme);
        });

    </script>
</head>
<body>

    <button id="btn">點擊我</button>
</body>
</html>

 

 事件監聽的三種方法:dom

一、直接在html上添加事件(不建議)函數

強耦合,不利用代碼複用spa

二、DOM 0級code

一個元素只能綁定一個事件的限制htm

若是綁定了多個事件,後面的會覆蓋掉前面的blog

二、DOM 2級事件

一個事件能夠綁定多個監聽函數ip

還能夠定義事件捕獲和事件冒泡input

btn.addEventListener("click", fn, false);  第三個參數默認是false

btn.attachEvent("onclick", fn);  IE的事件監聽函數attachEvent

document.body.addEventListener("load", init);

document.body.attachEvent("onload", init);

function init(){}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
        input{
            display: block;
            margin-bottom:10px;
        }
        .active{
            color:orange;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){

            // DOM 0級
            var btn3 = document.querySelector("#btn3");
            btn3.onclick=function(){
                alert("hello3~");
            }

            var btn4 = document.querySelector("#btn4");
            function click4(){
                alert("hello4~");
            }
            btn4.onclick=click4;


            // DOM 2級
            var btn5 = document.querySelector("#btn5");
            //事件句柄
            var click5 = function(){
                alert("hello5~");
            }
            //這裏的clickme不須要加括號
            btn5.addEventListener("click", click5);            

        });
    </script>
</head>
<body>
    <!-- 直接加在HTML上的兩種方式 -->
    <button id="btn1" onclick="alert('hello1~')">按鈕1</button>
    <!-- 這裏的click1()須要加括號 -->
    <button id="btn2" onclick="click2()">按鈕2</button><br>

    <!-- DOM 0級 -->
    <button id="btn3">按鈕3</button>
    <button id="btn4">按鈕4</button><br>

    <!-- DOM 2級 -->
    <button id="btn5">按鈕5</button>

    <script>
        // 忽然發現這個函數只能在btn的後面,而不能在前面
        // 即便用了domReady也不行哎
        function click2(){
            alert("hello2~");
        }
    </script>
</body>
</html>
相關文章
相關標籤/搜索