Javascript 未捕获的类型错误:无法读取未定义的属性“添加”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42081130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property 'add' of undefined
提问by sespler
I have the following code written in my .jsfile:
我在我的.js文件中编写了以下代码:
var tiles = document.querySelectorAll(".tile");
var tileNumbers = ["one", "two", "three", "four"];
for(var i = 0; i < tiles.length; i++){
var num = Math.floor(Math.random() * tileNumbers.lenth);
tiles.classList.add(tileNumbers[num]);
tileNumbers.pop(num);
}
The .tileare 4 <div>'s in the .html file, and I am trying to add a class each of the four tiles separately. The classes are held in tileNumbers. When I run the code in Chrome I get the error:
该.tile4个<div>的在.html文件,并且我想加个班四个砖分开。课程在tileNumbers. 当我在 Chrome 中运行代码时,出现错误:
"Uncaught TypeError: Cannot read property 'add' of undefined."
“未捕获的类型错误:无法读取未定义的属性‘添加’。”
I am pretty sure everything is spelled correctly. Please help!
我很确定一切都拼写正确。请帮忙!
回答by Golo Roden
You want to call addon the tile, but try to access the addfunction of the tilesarray itself. This does not exist.
您想add在 tile上调用,但尝试访问数组本身的add函数tiles。这不存在。
What you need to do is to access the addfunction of each individual tile. To do so, first get it:
您需要做的是访问add每个单独磁贴的功能。为此,首先获取它:
var tile = tiles[i];
Then, change your call to
然后,将您的呼叫更改为
tile.classList.add(…);
(You could also omit the temporary variable tile, and use tiles[i].classList.adddirectly. But IMHO using a dedicated variable makes the code more clear to read.)
(您也可以省略临时变量tile,tiles[i].classList.add直接使用。但恕我直言,使用专用变量会使代码更清晰易读。)
Another option, which may be even better, is to use forEach. Since you use the ionly for accessing the current element and nothing else, you basically want to perform an action on each element. You can do it like this as well (and, for bonus points, this even protects you against off-by-one errors):
另一种可能更好的选择是使用forEach. 由于您使用ionly 来访问当前元素而不是其他任何东西,因此您基本上希望对每个元素执行一个操作。您也可以这样做(并且,对于奖励积分,这甚至可以保护您免受一对一错误的影响):
tiles.forEach(function (tile) {
// ...
});
Then, within the function body, you automatically have a variable tilethat you can access in the way you want to.
然后,在函数体内,您将自动拥有一个tile可以按您想要的方式访问的变量。
That's it :-)
就是这样 :-)
回答by Abdennour TOUMI
tiles[i].classList.add(tileNumbers[num]);
Not
不是
tiles.classList.add(tileNumbers[num]);

