javascript之单击按钮时如何运行此功能
52php
阅读:14
2024-12-31 21:38:35
评论:0
我做了一个函数,当你按下一个按钮时,它会显示一个随机的报价,问题是这个函数在页面加载时运行。所有代码都按预期工作,但我找不到它立即运行的原因。我认为问题是我在 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>
请您参考如下方法:
所以这里有 2 个问题。一个是下面的代码在加载时正确运行:
var result = generateQuote(quotesArray);
quoteText.innerHTML = result.quote;
author.innerHTML = result.author;
这会导致在页面加载时呈现报价。您应该将其包装在一个函数中以防止这种情况发生。例如你可以这样写:
function generateQuote(array) {
var quoteIndex = Math.floor(Math.random() * quotesArray.length);
var randomQuote;
for (var i = 0; i < array.length; i++) {
randomQuote = array[quoteIndex];
}
return randomQuote;
}
function renderQuote() {
var result = generateQuote(quotesArray);
quoteText.innerHTML = result.quote;
author.innerHTML = result.author;
}
然后点击按钮,你可以绑定(bind) renderQuote:
button.addEventListener('click', renderQuote);
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。