国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 得荣县| 桦川县| 逊克县| 海伦市| 扶余县| 黄山市| 根河市| 新乡县| 星座| 陈巴尔虎旗| 宝山区| 祁东县| 开阳县| 五台县| 额尔古纳市| 枞阳县| 陵川县| 尼玛县| 淅川县| 曲阳县| 仁寿县| 邳州市| 栾城县| 南康市| 万全县| 沧州市| 无极县| 松滋市| 亚东县| 德令哈市| 福清市| 宿州市| 青田县| 乐安县| 太谷县| 湖南省| 古浪县| 休宁县| 华安县| 虞城县| 巴南区|