javascript - Random/new text on page refresh and page load
问题描述
I have a list of facts that I wish to change on page refresh and/or page load.
All the solutions I've come across involve having a button, which I do not want.
function newFact() {
var randomFact = Math.floor(math.random() * facts.length);
document.getElementById('factDisplay').innerHTML = facts[randomFact]
}
So I've got a function that randomly pulls one string (fact) from a list of facts (var facts). I wish to make it such that every refresh/reload of the HTML page will generate a new fact.
EDIT: I called my script using <body onload="newFact()">
. Thanks for all your help!
解决方案
Put it as an IIFE (Immediately invoked function expression) anywhere in your script.
(function newFact() {
var facts = ['Fact 1', 'Fact 2', 'Fact 183'];
var randomFact = Math.floor(Math.random() * facts.length);
document.getElementById('factDisplay').innerHTML = facts[randomFact];
})();
<div id="factDisplay"></div>
IIFEs get (forcibly) executed before any other normal functions in JS. So on every page load/refresh this will be executed first, and show different result each time.
推荐阅读
- python - 在字典中添加字典 for 循环
- api-gateway - REST API 和 API 网关有什么区别?
- spock - spock DetachedMockFactory 的推荐使用方式
- javascript - 为什么初始值没有变化?
- python - 在为 jupyter notebook 设置路径后,我无法在 pycharm 中导入模块
- c# - 打印到 PDF 很好,但打印到打印机会给出空白页(WPF 中的 XPS Doc)
- python-3.x - 使用 tkinter 在标题栏上获取事件
- git - PR 完成后,Jenkins 将禁用 GitHub 分支
- azure-devops - 使用 WinRM 的 IIS Web 应用程序部署未在用户名中转义 $
- sql - 在子查询 postgresql 中获取值