第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定

在改變背景色中,關于this的一點問題

?window.onload = function(){

? ? ? ? ? ? ? ? ??

? ? ?// 鼠標移動改變背景,可以通過給每行綁定鼠標移上事件和鼠標移除事件來改變所在行背景色。

? ? ? ? var tr=document.getElementsByTagName('tr');

? ? ? ? var len=tr.length;

? ? ? ? for(var i=0;i<len;i++) {

? ? ? ? ? ? tr[i].onmouseover=function(){this.style.backgroundColor="#999";}

? ? ? ? ? ? tr[i].onmouseout=function(){this.style.backgroundColor="#fff";}

? ? ? ? }?

}




為什么把上面代碼的this改成tr[i]就無效了呢?也就是:

for(var i=0;i<len;i++) {

? ? ? ? ? ? tr[i].onmouseover=function(){tr[i].style.backgroundColor="#999";}

? ? ? ? ? ? tr[i].onmouseout=function(){tr[i].style.backgroundColor="#fff";}

? ? ? ? }?


正在回答

3 回答

mark一下,雖然還是不太懂

http://www.cnblogs.com/syf/archive/2012/10/04/2711828.html

0 回復 有任何疑惑可以回復我~

@王大濤

for(var i=0;i<tr.length;i++){

tr[i].index = i; //這里的index可以自己隨便換,也就是給標簽tr自定義的屬性. 比如:tr[i].a = i;

tr[i].onmouseover=function(){tr[tr.index].style.backgroundColor="#999"}

tr[i].onmouseout=function(){tr[tr.index].style.backgroundColor="#fff";}

}


你這段的實現(xiàn)效果是不正確的。運行的效果實際上tr[tr.index]==tr[2]

而我原來的tr[i]位于function中,實際效果是tr[i]==tr[3] //如果審查元素手動添加一行<tr>就能發(fā)現(xiàn)。

據(jù)我朋友的解釋,這是帶參數(shù)的function在for語句中的問題。只是我不太理解其中的道理。


0 回復 有任何疑惑可以回復我~

這個問題不是 this的問題,而是變量作用域的問題;

?tr[i].onmouseover=function(){tr[i].style.backgroundColor="#999";}這行代碼中黑體的ti[i]是無效的.

因為在function(){tr[i].style.backgroundColor="#999";}這個函數(shù)中i的值是不知道的.所以不能用tr[i].style.backgroundColor="#999";這樣來設置樣式.?

一般我們會直接用this代表當前tr.如果不用this,我們可以用給標簽添加屬性的方法比如:

for(var i=0;i<tr.length;i++){

tr[i].index = i; //這里的index可以自己隨便換,也就是給標簽tr自定義的屬性. 比如:tr[i].a = i;

tr[i].onmouseover = function(){ tr[tr.index].style.backgroundColor = "#999"}

tr[i].onmouseout=function()tr[tr.index].style.backgroundColor="#fff";}

}

0 回復 有任何疑惑可以回復我~
#1

Huajie 提問者

不對。詳細見我后面的回復。
2016-03-07 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消
JavaScript進階篇
  • 參與學習       468768    人
  • 解答問題       22442    個

本課程從如何插入JS代碼開始,帶您進入網(wǎng)頁動態(tài)交互世界

進入課程

在改變背景色中,關于this的一點問題

我要回答 關注問題
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號