【问题标题】:How to create a randomized quote generator?如何创建随机报价生成器?
【发布时间】:2022-01-21 07:55:51
【问题描述】:

我正在构建一个积极的肯定生成器,并且想要一些输入。我试图弄清楚如何生成报价。我已经写下了 Math.random。这是一些代码。

function newQuote() {
  var randomNumber = Math.floor(Math.random() * (positiveAff.length));
  document.getElementById(affirmations).innerHTML = positiveAff[randomNumber];
}
<body>
  <h1>Positive Affirmations Generator</h1>

  <div id="affirmations">

  </div>
  <button onclick="newQuote()">Click to change affirmations</button>


  <script src="script.js"></script>
</body>

【问题讨论】:

  • 什么是positiveAff?它是在哪里定义的?
  • positiveAff 被定义为一个包含我没有包含的引号的数组。很抱歉造成误解。
  • 请在您的代码中包含该数组。另外,您在使用此代码时遇到了哪些问题?
  • 对不起。我不确定要添加它。由于某种原因,它不会生成引号。
  • 请使用该数组更新帖子,以便您的问题可以正确重现。

标签: javascript quotes


【解决方案1】:

我的答案是假设您将拥有一系列引号。

const positiveAff = [
{ id: 1, quote: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit, dolores!" },
{ id: 2, quote: "consectetur adipisicing elit. Velit, dolores!" },
{ id: 3, quote: "amet consectetur adipisicing elit. Velit, dolores!" }]

const button = document.getElementById('button')

button.addEventListener("click", function () {
  newQuote()
})
function newQuote() {
  var randomNumber = Math.floor(Math.random() * (positiveAff.length));
  document.getElementById("affirmations").innerHTML = positiveAff[randomNumber].quote;
}
<h1>Positive Affirmations Generator</h1>
<div id="affirmations"></div>
<button id="button">Click to change affirmations</button>

【讨论】:

    【解决方案2】:

    根据您的 sn-p,问题不在于您获取报价的代码。问题是你是怎么写的。在document.getElementById(affirmations) 中,您使用affirmations 作为变量,该变量从未定义。我把它改成了一个字符串,并添加了一个数组,现在它可以工作了。

       positiveAff = [
      "Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit, dolores!",
      "consectetur adipisicing elit. Velit, dolores!",
      "amet consectetur adipisicing elit. Velit, dolores!"
    ]
    
    function newQuote() {
      var randomNumber = Math.floor(Math.random() * (positiveAff.length));
      document.getElementById('affirmations').innerHTML = positiveAff[randomNumber];
    }
    <h1>Positive Affirmations Generator</h1>
    <div id="affirmations"></div>
    <button onclick="newQuote()">Click to change affirmations</button>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 2021-03-31
      • 1970-01-01
      • 2017-05-01
      • 2021-10-31
      • 2014-05-05
      • 1970-01-01
      相关资源
      最近更新 更多