JavaScript 无法找到函数

标签 javascript function

我的 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/

相关文章:

c - 之前的声明 - was Here 和 "conflicting types for put_non_bloccante"

c - 在C中如何将函数作为参数传递?

javascript - 谷歌地图 SVG 标记填充颜色

javascript - 如何更改使用 javascript 创建的单元格内容的字体大小

javascript - 背景图像的 Owl Carousel 不起作用

javascript - 在 Javascript 中的数字左侧填充零

javascript - 如何在 Chrome 中禁用 console.trace 树?

c++ - 我们从哪里得到这个参数的值?

Javascript - 为什么从函数返回 array.push(x) 不会将元素 x 插入数组?

c - 这个程序有什么作用? (自调用main函数+getchar)