在函数内调用的函数不起作用

时间:2018-10-10 12:28:21

标签: javascript

我将要发布它,因为找不到解决该问题的答案。

我有以下代码,其中我更改了某些div的背景色。 我有一个针对该changeSqColor()的函数,该函数在另一个函数中调用时不起作用。 这里有什么问题? (定义了数组颜色,元素数= div数)

var squares = document.getElementsByClassName("square");

function changeSqColor() {
    for (var i = 0; i < squares.length; i++) {
        squares[i].style.background = colors[i];
    }
}

changeSqColor(); // this works ok colors are changes

function resetGame() {
    //other commands
    changeSqColor(); //this one doesnt work, in console it says 'undefined'
}

3 个答案:

答案 0 :(得分:2)

您有时必须在代码中调用function resetGame。您尚未调用resetGame

var squares = document.getElementsByClassName("square");
let colors = ['red','green','blue','white','yellowgreen'];
function changeSqColor() {
  for (var i = 0; i < squares.length; i++) {
     squares[i].style.background = colors[i]; 
   }
setTimeout(function(){resetGame();},3000);// call resetGame Function.
}
changeSqColor(); 

function resetGame (){
 for (var i = 0; i < squares.length; i++) {
  squares[i].style.background = colors[0]; 
  }
  setTimeout(function(){changeSqColor();},3000);
  // As you mentioned calling changeSqColor() 
}
<div class="square">1</div>
<div class="square">2</div>
<div class="square">3</div>
<div class="square">4</div>
<div class="square">5</div>

答案 1 :(得分:0)

changeSqColor(); -之所以有效,是因为您通过()括号显式执行了方法调用。

resetGame()您只是通过不执行方法来定义方法。如果您想定义函数resetGame()并一次性执行它,我们可以这样做,

(function resetGame() {
    //other commands
    changeSqColor(); //this one doesnt work, in console it says 'undefined'
})()

如果您正在调用resetGame()方法,那么在执行resetGame()时,如果函数changeSqColor()不在范围内/不可访问,则将出现“未定义”。

答案 2 :(得分:0)

好的,我知道是什么问题。 我宣布局部变量为颜色的新地方。

之前

function resetGame (){
var colors = generateRandomColors(6);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
messageDisplay.textContent = "";
changeSqColor();
}

之后:

function resetGame (){
colors = generateRandomColors(6); // var removed
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
messageDisplay.textContent = "";
changeSqColor();
}

愚蠢的错误;-)

相关问题