js學習總結----事件委託和事件代理

來源:互聯網
上載者:User

標籤:htm   doc   pre   isp   order   tag   ntb   log   border   

1、什麼是事件委託/事件代理

  利用事件的冒泡傳播機制(觸發當前元素的某一個行為,它父級所有元素的相關行為都會被觸發),如果一個容器中有很多元素都要綁定點擊事件,我們沒有必要一個個的綁定了,只需要給最外層容器綁定一個點擊事件即可,在這個方法執行的時候,通過事件來源的區分來進行不同的操作。

  具體小案例如下:  

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title>    <style>        *{            margin:0;            padding:0;            font-size:14px;        }        html,body{            width:100%;            height:100%;            overflow:hidden;        }        #box{            position:absolute;            left:50%;            top:50px;            width:100px;            height:30px;            margin-left:-50px;            line-height:30px;            text-align:center;            border:1px solid #2489cc;        }        #mark{            position:absolute;            top:30px;            left:-1px;            width:300px;            height:100px;            line-height:100px;            text-align:center;            background:#ffe470;            border:1px solid #2489cc;        }    </style></head><body>    <div id=‘box‘>        <span>購物車</span>        <div id="mark" style=‘display:none‘>                查看購物車的詳細資料        </div>    </div>    <script>         var mark = document.getElementById(‘mark‘);        document.body.onclick = function(e){            e = e || window.event;            e.target = e.target || e.srcElement;            //如果點擊的是box或者是#box下的span,我們判斷mark是否顯示,顯示讓其隱藏,反之讓其顯示            if(e.target.id==="box" || (e.target.tagName.toLowerCase()==="span" && e.target.parentNode.id===‘box‘)){                if(mark.style.display === "none"){                    mark.style.display === "block"                }else{                    mark.style.display === "none"                }                return;            }            //如果事件來源是#mark,不進行任何的操作            if(e.target.id==="mark"){                return;            }            mark.style.display === "none"        }    </script></body></html>

 

js學習總結----事件委託和事件代理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.