【问题标题】:Coffescript For-Loop Not Working with Additional Variable CreatedCoffeescript For-Loop 不适用于创建的附加变量
【发布时间】:2017-01-25 16:50:12
【问题描述】:

所以我是使用 coffescript 的新手,我无法弄清楚我做错了什么。我使用while循环使它工作,但我只想知道如何使用for循环使它工作。循环只运行一次并返回错误 "Uncaught TypeError: Cannot read property 'style' of undefined"

squares = document.querySelectorAll(".square")

我的 cs 代码如下所示:

function = (col) ->
    for squares in squares
        squares.style.background = col

js 输出:

changeColor = function(col) {
  var j, len;
  for (j = 0, len = squares.length; j < len; j++) {
    squares = squares[j];
    squares.style.background = col;
  }
};

js 输出被接受:

changeColor = function(col) {
  var j;
  for (j = 0; j < squares.length; j++) {
    squares[j].style.background = col;
  }

据我了解,转换后的 js 是正确的,但它不会接受声明的附加变量。尽管如此,我可能是错的。感谢您的任何帮助。

【问题讨论】:

  • 你不是说for square in squares吗?
  • @muistooshort 嗨。对不起。但我不这么认为。 “squares”是我在cs/js中使用的变量,“square”是我在html中使用的类。我尝试使用 square 并呈现以下结果。
  • for (i = 0, len = squares.length; i &lt; len; i++) { square = squares[i]; squares[j].style.background = col; }
  • 但你说的是for x in x,这没有任何意义。您不希望您的循环变量与您正在迭代的变量具有相同的名称。因此我建议使用for square in squares 而不是for squares in squares

标签: javascript for-loop coffeescript


【解决方案1】:

一般来说,如果 Coffeescript(因此是 Javascript)给您一条错误消息,其中包含 undefined,那么您的调用目标不存在。

所以在你的情况下,它说squaresundefined 并且undefined 确实没有名为background 的属性。我怎么知道这个?仅仅因为使用style的唯一行是

squares.style.background = col

所以stylesquares 调用,而squares 未定义。

现在下一个问题显然是为什么squares未定义。我的猜测:您的文档中没有 square 类的 html 元素。做吧

squares = document.querySelectorAll(".square")
console.log(squares)

查看对querySelectorAll 的调用产生了什么

【讨论】:

  • 嗨。谢谢您的答复。然而,我的 html 中有一个方形类。我很抱歉,因为我为我的文件使用了相当混乱的命名。 Chrome 控制台:[div.square, div.square, div.square, div.square, div.square, div.square]
猜你喜欢
  • 1970-01-01
  • 2022-12-03
  • 2017-03-20
  • 2018-09-08
  • 2015-11-02
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
  • 2018-06-06
相关资源
最近更新 更多