我正在构建一个随机报价生成器作为我的第一个javascript项目。我可以使报价正常运行,但是我希望在有人首次访问该网站以及单击该按钮时显示这些报价。
到目前为止,这是我的代码:
LiteDB
和javascript:
<div id="quoteDisplay">
<!-- Quotes will display here -->
</div>
<!-- Center is added for button placement -->
<button onclick="newQuote()">New Quote</button>
<script type="text/javascript" src="ron.js"></script>
有关在用户首次访问页面时添加哪些内容以显示报价的建议?
答案 0 :(得分:2)
只需在页面加载时调用函数即可
window.addEventListener('load', newQuote, true);
答案 1 :(得分:1)
要使功能在用户加载页面后立即运行,请在脚本末尾添加此功能:
window.onload = newQuote;
或使用html body属性
<body onload="newQuote()">
答案 2 :(得分:1)
只需在脚本定义后调用newQuote();
,因为已经在<script>
标记上方处理了相关的HTML。无需添加onload
事件监听器。
var quotes = ["quote 1", "quote 2", "quote 3"];
function newQuote() {
var randomNumber = Math.floor(Math.random() * quotes.length);
document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}
newQuote();
<div id="quoteDisplay">
<!-- Quotes will display here -->
</div>
<!-- Center is added for button placement -->
<button onclick="newQuote()">New Quote</button>
<!-- <script type="text/javascript" src="ron.js"></script> -->
答案 3 :(得分:1)
一种摆脱使用干扰性JavaScript的方法(使用onclick
,onblur
之类的内联事件处理程序)如下:
// the quotes:
let quotes = ["quote 1", "quote 2", "quote 3", ],
// the button to which the click event is bound:
button = document.querySelector('#changeQuote'),
// a created click-event (any other name could be used
// but since we're binding a click event-handler it
// it makes sense to create a named 'click' event:
clickEvent = new Event('click');
// using EventTarget.addEventListener() to bind the newQuote()
// function - note the deliberate lack of parentheses, it's not
// a mistake - as the event-handler for the 'click' event:
button.addEventListener('click', newQuote);
// here we trigger the event using EventTarget.dispatchEvent():
button.dispatchEvent(clickEvent);
function newQuote() {
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}
<div id="quoteDisplay"></div>
<button id="changeQuote">Change quote</button>
参考文献: