鼠標(biāo)經(jīng)過改變背景顏色問題
window.onload?=?function(){ ???var?tableRows=document.getElementsByTagName("tr"); ???for(var?i=0;i<tableRows.length;i++){ ???????tableRows[i].onmouseover=function(){? ???????????tableRows[i].style.backgroundColor="yellow"; ?????????} ?????????tableRows[i].onmouseout=function(){ ?????????????tableRows[i].style.backgroundColor="#CCC"; ??????????} ?????} ??}
為什么這種設(shè)置顏色時(shí),總對(duì)初始那兩行報(bào)Cannot read property 'style' of undefined錯(cuò)誤,然后只在新增加一行的上面生效。然后我改成圖片那種就沒有問題了。我感覺這是差不多的啊。
我的添加代碼:
2018-11-21
?
tableRows[i].style.backgroundColor=
"yellow"
;
?
tableRows[i].style.backgroundColor=
"#CCC"
;
你把你的這兩行代碼改成 :this.
style.backgroundColor=
"yellow"
;this
.style.backgroundColor=
"#CCC"
;
2018-11-22
for循環(huán)時(shí)用var定義存在變量提升問題,
tableRows[i].onmouseover=
function
(){
tableRows[i].style.backgroundColor=
"yellow"
;
};當(dāng)執(zhí)行移入移除的時(shí)候i已經(jīng)循環(huán)到tableRows.length;所以只能是最后一個(gè)有效果吧。將tableRows[i]改為this時(shí)有效果是因?yàn)?,this指向的是調(diào)用這個(gè)方法的對(duì)象,
tableRows[i].onmouseover=
function
(){this
.style.backgroundColor=
"yellow"
;
};this指向的就是tableRows[i]。
我覺得是這個(gè)樣子,僅供參考
2018-11-21
函數(shù)之間存在作用域,具體原理與理論我不太清楚去了.. 大概意思就是
tableRows[i]
是局部的。。不是全局