国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > JavaScript > 正文

深入淺析JavaScript中對(duì)事件的三種監(jiān)聽方式

2019-11-20 11:30:14
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

事件(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è)事件。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 冷水江市| 茌平县| 满城县| 涞水县| 大足县| 大兴区| 江西省| 平舆县| 宁化县| 肇州县| 黄石市| 景泰县| 汶上县| 石嘴山市| 长寿区| 乌兰县| 土默特右旗| 湘潭县| 蕉岭县| 曲沃县| 仪陇县| 六安市| 禄丰县| 陵川县| 什邡市| 东辽县| 湛江市| 龙里县| 象山县| 娄底市| 平乐县| 牟定县| 博白县| 随州市| 章丘市| 仙游县| 神池县| 新绛县| 东乡族自治县| 延长县| 堆龙德庆县|