事件(Event)是JavaScript應(yīng)用跳動(dòng)的心臟,也是把所有東西粘在一起的膠水,當(dāng)我們與瀏覽器中Web頁(yè)面進(jìn)行某些類型的交互時(shí),事件就發(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的方式獲取對(duì)象,并加載事件:
<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)聽方式,是使用標(biāo)準(zhǔn)的addEventListener方式和IE私有的attachEvent方式,因?yàn)镮E的attachEvent方式在參數(shù)傳遞時(shí)的缺陷,這個(gè)問(wèn)題被搞得稍許有些復(fù)雜了:
<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>在綁定多個(gè)相同的事件的時(shí)候,前兩種方法會(huì)產(chǎn)生覆蓋,而第三中方法則會(huì)同時(shí)執(zhí)行多個(gè)事件。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注