【问题标题】:Onclick function is returning reference errorOnclick 函数返回引用错误
【发布时间】:2021-10-15 19:17:49
【问题描述】:

这似乎应该是基本的,但我不知道为什么会这样。尝试在 html 中使用 javascript 函数时遇到未捕获的引用错误。

我使用我创建的 randomQuote 函数创建了一个生成新报价的按钮(上下文中的代码笔:https://codepen.io/cpmcclure/pen/MWvKaVp):

注意:我不知道如何将 jquery 添加到此示例中,但它包含在 codepen 中

// create array for quotes
let quoteList = [];

// retrieve quotes and assign them to quoteList array
const settings = {
  "async": false,
  "crossDomain": true,
  "url": "https://type.fit/api/quotes",
  "method": "GET"
}

$.ajax(settings).done(function (response) {
  const data = JSON.parse(response);
  quoteList = data;
});

// create display quote variable
let displayQuote = {};

// function to assign random quote to displayQuote on a click event
function randomQuote() {
   displayQuote = quoteList[Math.round(Math.random() * 1643)];
}
<button id="new-quote" onclick="randomQuote()">New Quote</button>

我查看了其他使用相同语法访问 html 中的 js 函数的笔,知道我做错了什么吗?

我知道我得到了正确的引号,如果我在 JavaScript 中调用 randomQuote,它会做它应该做的事情,似乎我在让 html 和 js 进行通信时遇到了问题。

【问题讨论】:

    标签: javascript html referenceerror


    【解决方案1】:

    这可能是因为您使用 jquery 进行 ajax 并且您没有在代码中添加库。

    {
      "message": "Uncaught ReferenceError: $ is not defined",
      "filename": "https://stacksnippets.net/js",
      "lineno": 23,
      "colno": 1
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2014-07-24
    • 2021-12-13
    相关资源
    最近更新 更多