我创建了一个函数,当你按下按钮时会显示一条随机引用语,但问题在于该函数在页面加载时就运行了。所有代码都按照预期工作,但我找不到它立即运行的原因。我认为问题在于我在
我希望有人能帮我找到问题,以下是代码:
JavaScript:
var result = generateQuote(quotesArray);
外部调用函数本身,但当我将其放置在函数本身内部时,它会出错。我希望有人能帮我找到问题,以下是代码:
JavaScript:
const quotes = new Object();
const quotesArray = [{
quote: "“Be yourself, everyone else is already taken.”",
author: "- Oscar Wilde",
} , {
quote: "“Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.”",
author: "― Albert Einstein",
} , {
quote: "“The important thing is not to stop questioning. Curiosity has its own reason for existing.”",
author: "― Albert Einstein"
} , {
quote: "“Expect everything, I always say, and the unexpected never happens.”",
author: "― Norton Juster"
} , {
quote: "“What lies behind you and what lies in front of you, pales in comparison to what lies inside of you.”",
author: "― Ralph Waldo Emerson"
} , {
quote: "“We are part of this universe; we are in this universe, but perhaps more important than both of those facts, is that the universe is in us.”",
author: "―Neil deGrasse Tyson"
}]
const button = document.querySelector('.generateQuote');
const author = document.querySelector('#quoteAuthor');
const quoteText = document.querySelector('#quote');
button.addEventListener('click', generateQuote);
function generateQuote(array) {
var quoteIndex = Math.floor(Math.random() * quotesArray.length);
for (var i = 0; i < array.length; i++) {
var randomQuote = array[quoteIndex];
}
return randomQuote;
}
var result = generateQuote(quotesArray);
quoteText.innerHTML = result.quote;
author.innerHTML = result.author;
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Quote Generator</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="border">
<div class="quoteContainer">
<h2 class="title">Quote Generator</h2>
<button class="generateQuote">Generate a inspiring quote</button>
<blockquote id="quote"><h2>quote</h2></blockquote>
<h3 id="quoteAuthor">Author of the quote</h3>
</div></div>
<script src="script.js"></script>
</body>
</html>
for
语句后的代码是无法到达的。 - Basickz