2016-06-07 17 views
1

該函數在每次啓動時應該將x增加1,從而迫使代碼在下次啓動時選擇不同的選項。爲什麼這個Javascript無法成功更改第二個mouseover的背景?

function changeBackground() { 
    var x = 0; 
    if (x % 2 === 0) { 
    document.getElementById("sample").style.backgroundColor = "purple"; 
    } 
    else { 
    document.getElementById("sample").style.backgroundColor = "white"; 
    } 
    x++; 
} 
var x = document.getElementById("sample"); 
x.onmouseover = changeBackground; 

這只是抓住一個標題,每次光標放在它上面時啓動changeBackground。背景色保持在紫色

回答

0

,因爲你把它每次都設置爲0,在函數的開始..你需要設置變量的函數

var x = 0; 
function changeBackground() { 
if (x % 2 === 0) { 
document.getElementById("sample").style.backgroundColor = "purple"; 
} 
else { 
document.getElementById("sample").style.backgroundColor = "white"; 
} 
x++; 
} 
var x = document.getElementById("sample"); 
x.onmouseover = changeBackground; 
+0

這是問題之外,謝謝。我也注意到我宣佈了兩次。 – DSATH

相關問題