深入淺析JavaScript中對事件的三種監(jiān)聽方式
事件(Event)是JavaScript應(yīng)用跳動的心臟,也是把所有東西粘在一起的膠水,當我們與瀏覽器中Web頁面進行某些類型的交互時,事件就發(fā)生了。
第一種監(jiān)聽方式,也是最普遍使用的方式,是直接在代碼上加載事件,產(chǎn)生效果:
<table> <tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'><td>text1</td><td>text2</td></tr> <tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'><td>text3</td><td>text4</td></tr> <tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'><td>text5</td><td>text5</td></tr> </table>
第二種監(jiān)聽方式,是使用DOM的方式獲取對象,并加載事件:
<table> <tr><td>text1</td><td>text2</td></tr> <tr><td>text3</td><td>text4</td></tr> <tr><td>text5</td><td>text5</td></tr> </table> <script> doms = document.getElementsByTagName('tr'); for(i=0;i<doms.length;i++) { doms[i].onmouseover = function() { this.style.backgroundColor = "red"; } doms[i].onmouseout = function() { this.style.backgroundColor = ""; } } </script>
第三種監(jiān)聽方式,是使用標準的addEventListener方式和IE私有的attachEvent方式,因為IE的attachEvent方式在參數(shù)傳遞時的缺陷,這個問題被搞得稍許有些復雜了:
<table> <tr><td>text1</td><td>text2</td></tr> <tr><td>text3</td><td>text4</td></tr> <tr><td>text5</td><td>text5</td></tr> </table> <script> doms = document.getElementsByTagName('tr'); function show_color(where) { this.tagName ? where = this : null where.style.backgroundColor = "red"; } function hide_color(where) { this.tagName ? where = this : null where.style.backgroundColor = ""; } function for_ie(where,how) { return function() { how(where); } } for(i=0;i<doms.length;i++) { try { doms[i].addEventListener('mouseover',show_color,false); doms[i].addEventListener('mouseout',hide_color,false); } catch(e) { doms[i].attachEvent('onmouseover',for_ie(doms[i],show_color)); doms[i].attachEvent('onmouseout',for_ie(doms[i],hide_color)); } } </script>
在綁定多個相同的事件的時候,前兩種方法會產(chǎn)生覆蓋,而第三中方法則會同時執(zhí)行多個事件。
相關(guān)文章
原生JS封裝_new函數(shù)實現(xiàn)new關(guān)鍵字的功能
這篇文章主要介紹了原生JS封裝_new函數(shù),實現(xiàn)new關(guān)鍵字的功能 ,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08echarts報錯:Error?in?mounted?hook的解決方法
最近又遇到了寫echarts的時候常遇到的一個錯誤,這篇文章主要給大家介紹了關(guān)于echarts報錯:Error?in?mounted?hook:?“TypeError:?Cannot?read?properties?of?undefined?(reading?‘init‘)“的解決方法,需要的朋友可以參考下2022-07-07Javascript遍歷Html Table示例(包括內(nèi)容和屬性值)
這篇文章主要介紹了Javascript如何遍歷Html Table(包括內(nèi)容和屬性值),需要的朋友可以參考下2014-07-07