所以我不熟悉使用coffescript,我无法弄清楚我做错了什么。我使用while循环使其工作,但我只是想知道如何使用for循环使其工作。循环只运行一次,并返回错误“Uncaught TypeError:无法读取未定义的属性'样式'
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是正确的,但它不接受声明的其他变量。尽管如此,我可能是错的。感谢您的任何帮助。
答案 0 :(得分:0)
一般情况下,如果Coffeescript(以及Javascript)给您一条错误消息,其中包含undefined
而不是您的通话目标。
因此,在您的情况下,它表示squares
为undefined
而undefined
确实没有名为background
的属性。我怎么知道这个?仅仅因为使用了唯一的whery style
行是
squares.style.background = col
因此style
上调用了squares
,squares
未定义。{/ p>
现在接下来的问题显然是为什么 squares
未定义。我的猜测:文档中没有类square
的html元素。只是做
squares = document.querySelectorAll(".square")
console.log(squares)
查看对querySelectorAll
的调用产生了什么