从 JavaScript 数组中获取随机值(单击按钮)


let text = ["hello", "world", "where", "list", "tes", "new"];
const btn = document.querySelector(".button");
btn.addEventListener("click", random);
const randomText = Math.floor(Math.random() * text.length);
function random() {
const pText = document.querySelector(".p-text");
const textRandom = (pText.innerHTML = `${text[randomText]}`);
}

嘿,伙计们,你能帮我吗? 单击按钮时如何仍然获得随机结果?

调用随机函数中的randomText。 因为它应该在每次单击按钮时运行

function random() {
const randomText = Math.floor(Math.random() * text.length);// here
const pText = document.querySelector(".p-text");
const textRandom = (pText.innerHTML = `${text[randomText]}`);
}
function random() {
const pText = document.querySelector(".p-text");
// move your randomText into function, so that it will have new value when the function is called.
const randomText = Math.floor(Math.random() * text.length);
const textRandom = (pText.innerHTML = `${text[randomText]}`);
}

最新更新