为什么这个全局变量不起作用?它完美地用作局部变量

时间:2018-08-14 01:28:23

标签: javascript scope global-variables

我想使“ 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 -->

3 个答案:

答案 0 :(得分:0)

您需要在代码中定义一个包含myColor值的元素,而您还没有定义r1c3BackgroundColor!只要有一个元素可以从中获取值,全局变量似乎就可以正常工作!

function r1c1BackgroundColor() { // Isn't working 
    myColor = document.getElementById("colorSelect").value;
    document.getElementsByClassName("tableBox")[0].style.backgroundColor = myColor;
}

function r1c2BackgroundColor() { // works fine
    myColor = document.getElementById("colorSelect").value;
    document.getElementsByClassName("tableBox")[1].style.backgroundColor = myColor;
}
function r1c3BackgroundColor() { // works fine
    myColor = document.getElementById("colorSelect").value;
    document.getElementsByClassName("tableBox")[2].style.backgroundColor = myColor;
}
<input id="colorSelect" value="#000000"/>
<table>
<tr>
<td id="r1c1" class="tableBox" onclick="r1c1BackgroundColor()">first</td>
<td id="r1c2" class="tableBox" onclick="r1c2BackgroundColor()">second</td>
<td id="r1c3" class="tableBox" onclick="r1c3BackgroundColor()">third</td>
</tr>
</table>

答案 1 :(得分:0)

您的全局变量是在首次加载文档时设置的,而在用户填写输入内容时永远不会更新。

如果您不想每次都编写该代码,请使其成为函数:

function getMyColor() {
    return document.getElementById("colorSelect").value;
}

然后您可以在所有需要它的地方调用它:

function r1c1BackgroundColor() { // Isn't working 
    document.getElementsByClassName("tableBox")[0].style.backgroundColor = getMyColor();
}

答案 2 :(得分:0)

问题在于,在将ID为 colorSelect 的元素附加到DOM(即文档)之前,将执行全局变量。

因此,当表达式的全局变量右侧,即 document.getElementById(“ colorSelect”)。value; 执行时,会发生什么,其值未定义,因此全局变量 myColor 值等于未定义。因此,无论您在哪里使用全局变量,其值都是不确定的。

它在局部变量的情况下起作用,因为在单击

时会调用 r1c2BackgroundColor 函数

<td id="r1c2" class="tableBox" onclick="r1c2BackgroundColor()"></td>

并且这次,id为 colorSelect 的元素已附加到DOM,因此局部变量值不会出现未定义的情况,并且可以正常工作。

要解决此问题,可以使用文档readystatechange事件和readyState属性。

总结,您可以执行以下操作。

var myColor;

document.onreadystatechange = function () {
  if (document.readyState === "interactive") {
    myColor = document.getElementById("colorSelect").value;
  }
}

function r1c1BackgroundColor() { 
    document.getElementsByClassName("tableBox")[0].style.backgroundColor = myColor;
}

function r1c2BackgroundColor() { 
    document.getElementsByClassName("tableBox")[1].style.backgroundColor = myColor;
}

希望有帮助!