馮春龍
2016-01-16 15:13:29
?????????var?tr?=?document.getElementsByTagName('tr');
????????????tr[0].onmouseover?=?function(){
??????????????tr[0].style.backgroundColor?=?'#ccc';?
????????????}
????????????tr[1].onmouseover?=?function(){
??????????????tr[1].style.backgroundColor?=?'#ccc';?
????????????}
????????????tr[2].onmouseover?=?function(){
??????????????tr[2].style.backgroundColor?=?'#ccc';?
????????????}上面的語句可以正常執(zhí)行,但是使用for循環(huán)的時(shí)候報(bào)錯(cuò)。循環(huán)方式如下:?????????var?tr?=?document.getElementsByTagName('tr');
????????????for(var?i=0;i<tr.length;i++){
??????????????tr[i].onmouseover?=?function(){
????????????????tr[i].style.backgroundColor?=?'#ccc';?
??????????????}????????????
????????????}求指點(diǎn)
4 回答
已采納

vone
TA貢獻(xiàn)23條經(jīng)驗(yàn) 獲得超2個(gè)贊
因?yàn)閛nmouseover事件是在鼠標(biāo)放上之后觸發(fā)的,而此時(shí)for循環(huán)早已結(jié)束,所以無論誰觸發(fā)的事件,i值永遠(yuǎn)固定不變.

qq_安伊偌拉_0
TA貢獻(xiàn)27條經(jīng)驗(yàn) 獲得超2個(gè)贊
這段代碼是先執(zhí)行循環(huán),然后給每個(gè)tr添加一個(gè)onmouseover事件,但是事件里面的內(nèi)容還讀取不到。等循環(huán)完之后,這時(shí)i==4,然后你把鼠標(biāo)挪進(jìn)去,執(zhí)行?tr[i].style.backgroundColor?=?'#ccc';?tr[4]為空,所以報(bào)錯(cuò)。

馮春龍
TA貢獻(xiàn)2條經(jīng)驗(yàn) 獲得超0個(gè)贊
stackoverflow 上有人回答,貼出來。
?????????var?tr?=?document.getElementsByTagName('tr'); ????????????for(var?i=0;i<tr.length;i++){ ??????????????tr[i].onmouseover?=?function(){ ????????????????//tr[i].style.backgroundColor?=?'#ccc';??更改為下一句 ????????????????this.style.backgroundColor?=?'#ccc'; ??????????????}???????????? ????????????}
為什么使用this 還不是很清楚,在學(xué)習(xí)中。
添加回答
舉報(bào)
0/150
提交
取消