问题:
I have this javascript code that collects the name from an array of string and return a random name, But everytime I fire the function, it is returning the same name; I nee...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I have this javascript code that collects the name from an array of string and return a random name, But everytime I fire the function, it is returning the same name; I need to refresh the web page to generate a new random name.
var items = ["Tony","Peter","Chris","Thor","Roger","Steve"];
var randomItem = items[Math.floor(Math.random() * items.length)];
function getRandom(){
document.getElementById("random").innerHTML = randomItem;
}
<button id="getRandom" onclick="getRandom()">Get Random name</button>
<span id="random">Click button to generate new name</span>
回答1:
You need to put the random function inside your getRandom()
function
var items = ["Tony","Peter","Chris","Thor","Roger","Steve"];
function getRandom(){
var randomItem = items[Math.floor(Math.random() * items.length)];
document.getElementById("random").innerHTML = randomItem;
}
<button id="getRandom" onclick="getRandom()">Get Random name</button>
<span id="random">Click button to generate new name</span>
回答2:
You create only once and never change randomItem
- that is why you're getting always the same item. Simplyfy your code as follows:
var items = ["Tony","Peter","Chris","Thor","Roger","Steve"];
function getRandom(){
document.getElementById("random").innerHTML = items[Math.floor(Math.random() * items.length)];
}
<button id="getRandom" onclick="getRandom()">Get Random name</button>
<span id="random">Click button to generate new name</span>