給元素添加事件,爲註冊事件或者綁定事件ide
註冊事件兩種方式函數
eventTarget.addEventListener(type, listener, [useCapture])
evetagrget.attachEvent(eventNameWithOn, callback)
<body> <button>傳統註冊事件</button> <button>addEventListener ie9以上</button> <button>attachEvent ie678</button> <script> var btns = document.querySelectorAll('button'); // 傳統註冊事件 btns[0].onclick = function () { alert('傳統方式') }; // addEventListener 添加多個不覆蓋 btns[1].addEventListener('click', function () { alert('ddEventListener ie9以上') }); btns[1].addEventListener('click', function () { alert('ddEventListener ie9以上---2') }); //attachEvent btns[2].attachEvent('click', function () { alert('attachEvent') }) </script> </body>
btns.onclick = null
eventTarget.removeEventListener(type, listener, [useCapture])
<body> <button>addEventListener ie9以上</button> <button>attachEvent ie678</button> <script> var btns = document.querySelectorAll('button'); // addEventListener 添加多個不覆蓋 btns[0].addEventListener('click', fn); function fn() { alert(222); this.removeEventListener('click', fn) } //attachEvent btns[1].attachEvent('click', fn1); function fn1() { alert(111); this.detachEvent('click', fn1) } </script> </body>