【发布时间】:2019-01-20 18:53:07
【问题描述】:
我想让“myColor”变量成为全局变量,这样我就不必将它粘贴到每个函数中,但我无法让它工作。我怎样才能让它工作?非常感谢任何帮助。
var myColor = document.getElementById("colorSelect").value; //this global variable isn't working
function r1c1BackgroundColor() { // Isn't working
document.getElementsByClassName("tableBox")[0].style.backgroundColor = myColor;
}
function r1c2BackgroundColor() { // works fine
var myColor = document.getElementById("colorSelect").value;
document.getElementsByClassName("tableBox")[1].style.backgroundColor = myColor;
}
<tr>
<td id="r1c1" class="tableBox" onclick="r1c1BackgroundColor()"></td>
<td id="r1c2" class="tableBox" onclick="r1c2BackgroundColor()"></td>
<td id="r1c3" class="tableBox" onclick="r1c3BackgroundColor()"></td>
<!-- etc -->
【问题讨论】:
标签: javascript scope global-variables