[英]Uncaught TypeError: Cannot read property foo of undefined
My JavaScript: 我的JavaScript:
todo.completed = !todo.completed;
ERROR: 错误:
Uncaught TypeError: Cannot read property 'completed' of undefined
at Object.toggleCompleted (script.js:34)
at Object.toggleCompleted (script.js:89)
at HTMLButtonElement.onclick ((index):33)
toggleCompleted @ script.js:34
toggleCompleted @ script.js:89
onclick @ (index):33
Am I missing something here? 我在这里想念什么吗?
It looks like you haven't declared the variable todo yet. 似乎您尚未声明变量todo。 Try something like todo = {};
尝试类似todo = {};
Let me know if you have questions! 如果您有任何问题,请告诉我!
The variable todo
has passed out of scope . 变量todo
已超出范围 。 It's probably declared in a function that is outside the closure of handlers.toggleCompleted()
when it is called. 可能是在调用handlers.toggleCompleted()
闭包之外的函数中声明的。
There are a couple of ways to fix this, but as the simplest you can just make todo
global: 有两种方法可以解决此问题,但最简单的方法就是将todo
设为全局:
var todo
and remove var
from the start. 找到var todo
并从头开始删除var
。 var todo = {};
在您的JS顶部添加var todo = {};
This will make todo
a global object that's always defined on your page. 这将使todo
成为始终在页面上定义的全局对象。
What's so confusing about it is that the code will work in Plunkr, glitch or codepen, but not a text editor and browser, because of the way those sites's routing is set up. 令人困惑的是,由于这些站点的路由设置方式,因此代码可以在Plunkr,小故障或Codepen中运行,但不能在文本编辑器和浏览器中运行。 In your index.html file you need to replace <script src = "filename.js></script>
with <script src="entire path to filename.js"></script>
在index.html文件中,您需要将<script src = "filename.js></script>
替换为<script src="entire path to filename.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.