首页 > 解决方案 > 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!

标签: javascripthtmlcss

解决方案


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.


推荐阅读