开发者问题收集

通过单击按钮从数组内的对象获取随机值

2017-02-27
120

单击按钮时,我需要从数组内的对象中获取随机字符串。但由于某种原因,我的代码无法执行。

var quotes = [{
    quote: "Quote1",
    source: "Source1"
  },
  {
    quote: "Quote2",
    source: "Source2"
  },
  {
    quote: "Quote3",
    source: "Source3"
  },
  {
    quote: "Quote4",
    source: "Source4"
  },
  {
    quote: "Quote5",
    source: "Source5"
  }
];

function getRandomquote() {
  var randomindex = Math.floor(Math.random() * (quotes.length));
  var quotesarr = quotes[randomindex];
  var objquote = quotesarr.quote;
  var objsource = quotesarr.source;

  document.getElementById("quote").innerHTML = objquote;
  document.getElementById("source").innerHTML = objsource;
}

function printQuote() {
  document.getElementById("loadQuote").onclick = getRandomquote;
}
printQuote();
<div class="container">
  <div id="quote-box">
    <p class="quote"> hello</p>
    <p class="source"> hello</p>
  </div>
  <button id="loadQuote" onclick="printQuote();">Show another quote</button>

我收到此错误消息:

Uncaught TypeError: Cannot set property 'innerHTML' of null at HTMLButtonElement.getRandomquote (randomtest1.js:27)

根据以下答案进行更新

我将 getElementById 更改为 getElementsByClassName ,现在没有错误消息。

但是当我单击按钮时,它不会更改元素。我相信我在 printQuote 函数上犯了一个错误。我搞不清楚。

3个回答

您需要按如下方式将 ID 添加到元素。或者使用 getElementsByClassName() 或使用 querySelector(".quote")

var objquote = "Hello";
var objsource = "World";
document.getElementById("quote").innerHTML=objquote;
document.getElementById("source").innerHTML=objsource;
<div id="quote-box">
  <p id="quote" class="quote"> hello</p>
  <p id="source" class="source"> hello</p>
</div>
DomeTune
2017-02-27

您无法使用 getElementById 通过元素的 class 检索元素。您需要指定 id 或使用 getElementsByClassName - https://developer.mozilla.org/en/docs/Web/API/Document/getElementsByClassName

var els = document.getElementsByClassName('test')
console.log(els.length)
<div class="test"></div>

在您的示例中:

<p class="quote" id="quote"> hello</p>
<p class="source" id="source"> hello</p>
G0dsquad
2017-02-27

请查看下面的工作代码。我已删除不需要的功能。

html

<div id="quote-box">
  <p class="quote">hello</p>
  <p class="source">hello</p>
</div>
<button id="loadQuote" onclick="getRandomquote();">Show another quote</button>

js

var quotes=[
{quote:"Quote1", source:"Source1"},
{quote:"Quote2", source:"Source2"},
{quote:"Quote3", source:"Source3"},
{quote:"Quote4", source:"Source4"},
{quote:"Quote5", source:"Source5"}
        ];
getRandomquote=function(){

var randomindex=Math.floor(Math.random()*(quotes.length));  
var quotesarr=quotes[randomindex];
document.getElementsByClassName("quote")[0].innerHTML=quotesarr.quote;
document.getElementsByClassName("source")[0].innerHTML=quotesarr.source;
}
Jijo Cleetus
2017-02-27