改變背景色的問題
var?trs?=?document.getElementsByTagName("tr"); ????????changeColor(trs);????? ????????????? ????????//循環(huán)在里面 ?????function?changeColor(trs){ ????????????for(var?i=0;i<trs.length;i++){ ????????????????var?tr?=?trs[i]; ????????????????tr.onmouseover?=?function(){ ????????????????????tr.style.backgroundColor?=?"#f2f2f2"; ????????????????} ????????????????tr.onmouseout?=?function(){ ????????????????????tr.style.backgroundColor?=?"#fff"; ????????????????} ????????????} ???????????? ?????}
var?trs?=?document.getElementsByTagName("tr"); ????????//循環(huán)在外面 ????????for(var?i=0;i<trs.length;i++){ ????????????????changeColor(trs[i]); ????????????}??????????? ?????function?changeColor(tr){ ????????????tr.onmouseover?=?function(){ ????????????????tr.style.backgroundColor?=?"#f2f2f2"; ????????????} ????????????tr.onmouseout?=?function(){ ????????????????tr.style.backgroundColor?=?"#fff"; ????????????}??????????? ?????}
循環(huán)在里面始終只有最后一行會有改背景色的效果,而循環(huán)在外面3行都有。為什么?
2016-03-10
大哥,差點(diǎn)被你坑了一把,害的我都開始懷疑人生了。。。。
你這是沒有考慮到tr的作用域呀。。。。。。。。。。。。。。
??//循環(huán)在里面
?????function?changeColor(trs){
????????????for(var?i=0;i<trs.length;i++){
????????????????var?tr?=?trs[i];
????????????????tr.onmouseover?=?function(){
????????????????????tr.style.backgroundColor?=?"#f2f2f2";//當(dāng)事件觸發(fā)時for循環(huán)早就結(jié)束了,tr也變成了最后一個tr了
????????????????????????????????????????????????????????????????????????????????//肯定改變的是最后一個呀
????????????????}
????????????????tr.onmouseout?=?function(){
????????????????????tr.style.backgroundColor?=?"#fff";
????????????????}
????????????}
?????}
===============================
var?trs?=?document.getElementsByTagName("tr");
????????//循環(huán)在外面
????????for(var?i=0;i<trs.length;i++){
????????????????changeColor(trs[i]);
????????????}???????????
?????function?changeColor(tr){
????????????tr.onmouseover?=?function(){
????????????????tr.style.backgroundColor?=?"#f2f2f2";//事件觸發(fā)了,for循環(huán)也結(jié)束了,但這里的tr只是個形參
????????????????//,不是for循環(huán)里面的那個tr,作用域只是這個匿名函數(shù)
????????????}
????????????tr.onmouseout?=?function(){
????????????????tr.style.backgroundColor?=?"#fff";
????????????}???????????
?????}
總結(jié)就是,前者的tr都是同一個,而后者的tr不是同一個,當(dāng)全局變量跟局部變量重名時,局部變量會覆蓋掉全局變量,關(guān)于這一點(diǎn),可以看看這里全局變量和局部變量
2016-04-14
不對吧,循環(huán)在里面,tr改成this就正常了