You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JS结合Fetch API开发随机名言生成器异常问题求助

问题代码错误点

  • 大小写拼写错误:DOM元素的HTML赋值属性为innerHTML,你的代码中写为innerHtml,JavaScript是大小写敏感语言,拼写错误会导致赋值操作完全失效
  • 模板字符串语法错误:你使用单引号包裹包含${变量}插值逻辑的内容,只有用反引号()包裹的模板字符串才会正常解析变量插值,单引号包裹只会把${quotes.content}`当做普通字符串输出
  • 缺失作者字段赋值逻辑:你已经提前获取了.author对应的DOM节点,但是代码中没有给该节点赋值接口返回的作者信息
  • 冗余变量:代码中声明的rem变量未参与任何业务逻辑,可直接删除

修正后的完整代码

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="Random.css">
    <title>Random Quotes Machines</title>
</head>
<body>
    <h1>Random Quotes </h1>
    <br> <br>
    <div class="container">
<p class="p">undefined </p>
<h6 class="author"> undefined</h6>
    </div>
    <button class="NextQuote" onclick="NextQuote()">NextQuote</button>
    <!-- <button class="previous">Previous</button> -->
    <script>
let container = document.getElementsByClassName("container");
let p = document.querySelector(".p");
let author = document.querySelector(".author");
function NextQuote (){
 fetch('https://api.quotable.io/random')
 .then(response => response.json())
  .then(quotes => {
    // 修正拼写+模板字符串语法
    p.innerHTML = `"${quotes.content}"`;
    // 补充作者字段赋值
    author.innerText = quotes.author;
  }  
    );
}
</script>
</body>
</html>

内容的提问来源于stack exchange,提问作者Zain Zubair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:45:03