2011-07-01 50 views
1

在這個函數中,它應該給菜單項(li)一個特定的背景(png)。然而;它沒有。它給所有的李時珍稱爲顏色「藍色」 :(背景 你看到問題「document.getElementById onmouseover and function」的行爲不如預期×108641

//Gives the menu items a style when hovering over it, in the sequence of the setting in the variable 'backgrounds', on top. 
var backgrounds = ["blue", "green", "pink", "purple"]; 

function MenuColorChange() { 
    for (var i = 0; i <= 10 ; i++) { 
     document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseover = function() { 
     this.style.backgroundImage= "url(images/" + backgrounds[(i % backgrounds.length)] + ".png)"; 
     } 
     document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseout = function() { 
     this.style.background = 'none'; 
     MenuActiveColor(); 
     } 
    } 
} 

HTML:?

 <ul> 
      <li id="custom-menu-item-id-1"> 
       <a href="#"> 
        Home 
       </a> 
      </li> 
          /* And 3 li's more... */ 
     </ul> 

回答

2

您使用onmouseover的功能外的closuse功能,在一次執行所有onmouseover處理有i保存價值,實現你見過想要做什麼:

//Gives the menu items a style when hovering over it, in the sequence of the setting in the variable 'backgrounds', on top. 
var backgrounds = ["blue", "green", "pink", "purple"]; 
function MenuColorChange() { 
    for (var i = 0; i <= 10 ; i++) { 
     document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseover = (function(valueOfI){ return function() { 
     this.style.backgroundImage= "url(images/" + backgrounds[(valueOfI % backgrounds.length)] + ".png)"; 
     }; })(i); 
     document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseout = function() { 
     this.style.background = 'none'; 
     MenuActiveColor(); 
     } 
    } 
} 
0

這使我感到驚訝。我希望它能使所有的背景變成粉紅色。發生這種情況的原因是,當您實際懸停在您的<li>元素上時,i將爲1010 % 4 = 2。你的數組的索引2是'pink'

爲了確保i是你想要當鼠標懸停鼠標移開事件被解僱,在功能包裝他們的價值。

function MenuColorChange() { 
    for (var i = 0; i <= 10 ; i++) { 
     (function(i) { 
      document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseover = function() { 
       this.style.backgroundImage = "url(images/" + backgrounds[(i % backgrounds.length)] + ".png)"; 
      } 
      document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseout = function() { 
       this.style.background = 'none'; 
       MenuActiveColor(); 
      } 
     }(i)); 
    } 
}