兩者有什么區(qū)別?求大神指教!
? ?為什么這樣可以,?
? window.onload = function(){
? ? ? ? ? var tr=document.getElementsByTagName("tr");
? ? ? ? ? for(var i= 0;i<tr.length;i++)
? ? ? ? ? {
? ? ? ? ? ? ? bgcChange(tr[i]);
? ? ? ? ? }
? ? ?// 鼠標移動改變背景,可以通過給每行綁定鼠標移上事件和鼠標移除事件來改變所在行背景色。
? ? ? } ? ? ? ??
function bgcChange(obj)
? ? ?{
? ? ? ? obj.onmouseover=function(){
? ? ? ? ? ? obj.style.backgroundColor="#f2f2f2";
? ? ? ? }
? ? ? ? obj.onmouseout=function(){
? ? ? ? ? ? obj.style.backgroundColor="#fff";
? ? ? ? }
}
這樣卻不行?
? window.onload = function(){
? ? var tr=document.getElementsByTagName("tr");
? ? ? ? for(var i= 0;i<tr.length;i++)
? ? ? ? ? {
? ? ? ? ? ? ? tr[i].onmouseover=function(){
? ? ? ? ? ? tr[i].style.backgroundColor="#f2f2f2"; ? ? ? ?}
? ? ? ? tr[i].onmouseout=function(){
? ? ? ? ? ?tr[i].style.backgroundColor="#fff"; ? ? ? ?}
? ? ? ? ? }
? ? ?}
2016-02-10
將? tr[i].style.backgroundColor="#f2f2f2"; 改為?this.style.backgroundColor="#f2f2f2";
2016-02-06
window.onload = function(){
? ?var tr=document.getElementsByTagName("tr");
? ?for(var i= 0;i<tr.length;i++)
? ?{
? ? ? ?tr[i].onmouseover=function(){
? ? ? ? ? ?this.style.backgroundColor="#f2f2f2"; ? ? ? ?}
? ? ? ?tr[i].onmouseout=function(i){
? ? ? ? ? ?this.style.backgroundColor="#fff"; ? ? ? ?}
? ?}
}
這樣就行;
首先
tr[i].onmouseover=function(){
? ? ? ? ? ? tr[i].style.backgroundColor="#f2f2f2"; ? ? ? ?}
這里 function里面的tr[i]因為變量作用域的關系是不存在的,把它換為當前對象this就解決了。