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