最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Randomnew text on page refresh and page load - Stack Overflow

programmeradmin0浏览0评论

I have a list of facts that I wish to change on page refresh and/or page load.

All the solutions I've e 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!

I have a list of facts that I wish to change on page refresh and/or page load.

All the solutions I've e 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!

Share Improve this question edited Jan 22, 2019 at 2:11 narypigeon asked Jan 21, 2019 at 11:45 narypigeonnarypigeon 1131 silver badge10 bronze badges 1
  • 1 why do you need a button? Call the newFact() function on page load event. – Fabrizio Calderan Commented Jan 21, 2019 at 11:48
Add a ment  | 

2 Answers 2

Reset to default 5

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.

Just put your script at the bottom/footer of your page and call it, like so :

const facts = ["1", "2", "3"];

!function newFact() {
  const randomFact = Math.floor(Math.random() * facts.length);
  document.getElementById('factDisplay').innerHTML = facts[randomFact];
}();
<div id="factDisplay"></div>

发布评论

评论列表(0)

  1. 暂无评论