我的 HTML:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Assignment A</title>
</head>
<body>
<h1>Fortune cookies!</h1>
<input type="text" id="input" placeholder="Add a fortune" />
<button onclick="cookie.add()">Add a fortune!</button><br />
<button onclick="cookie.fortune()">What does your fortune hold?</button>
<p id="output"></p>
<script src="3a.js"></script>
</body>
</html>
我的 JavaScript:
class Cookie
{
constructor()
{
this.fortunes = ["Insert meaningful quote here.", "insert meaningless quote here."];
}
add()
{
this.fortunes.push(document.getElementById("input").value);
document.getElementById("output").innerHTML = "fortune added!";
}
fortune()
{
document.getElementById("output").innerHTML = this.fortunes[Math.random(--this.fortunes.length)];
}
}
var cookie = new Cookie();
我觉得我完全失明了,但由于某种原因,每当我单击我制作的两个按钮中的任何一个时,我都会得到以下信息:
53a.html:12 Uncaught TypeError: cookie.fortune is not a function
at HTMLButtonElement.onclick (3a.html:12)
请帮忙。我不明白为什么我的JS无法调用这个函数。我肯定错过了一些微小的事情,但我完全陷入了狭隘的视野中。
最佳答案
尝试将 cookie
变量重命名为其他名称。看起来与 document.cookie
有冲突。
var cookie = new Cookie();
-> var cookieObj = new Cookie();
onclick="cookie.add()"
-> onclick="cookieObj.add()"
onclick="cookie.fortune()"
-> onclick="cookieObj.fortune()"
class Cookie
{
constructor()
{
this.fortunes = ["Insert meaningful quote here.", "insert meaningless quote here."];
}
add()
{
this.fortunes.push(document.getElementById("input").value);
document.getElementById("output").innerHTML = "fortune added!";
}
fortune()
{
console.log('fortune');
document.getElementById("output").innerHTML = this.fortunes[Math.random(--this.fortunes.length)];
}
}
var cookieObj = new Cookie();
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Assignment A</title>
</head>
<body>
<h1>Fortune cookies!</h1>
<input type="text" id="input" placeholder="Add a fortune" />
<button onclick="cookieObj.add()">Add a fortune!</button><br />
<button onclick="cookieObj.fortune()">What does your fortune hold?</button>
<p id="output"></p>
<script src="3a.js"></script>
</body>
</html>
关于JavaScript 无法找到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69362841/