function highlightRows() {
if(!document.getElementsByTagName) return false;
var tables = document.getElementsByTagName("table");
for(var i=0;i<tables.length;i++){
var rows = tables[i].getElementsByTagName("tr");
for(var j =0;j<rows.length;j++){
rows[j].onmouseover=function(){
//rows[j].style.fontWeight="bold"; //这样无效
this.style.fontWeight="bold";
}
rows[j].onmouseout=function() {
//rows[j].style.fontWeight="normal"; //这样无效
this.style.fontWeight="normal";
}
}
}
}
为什么注释的那两行不行,非要用this呢,这里this不是应该就是指代rows[j]么?
变量作用域问题
假设
rows.length = 9
最后一次for执行完毕的时候
j = 9
所有的匿名函数里面 j = 9,
绑定事件的时候j还不是9,执行的时候j已经全部是都是9了
也就是你绑定的所有事件都只对最后一个生效。
解决方法是用闭包