javascript - 从 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]}`);
}
嗨,伙计们,你能帮帮我吗?单击按钮时如何仍然获得随机结果?
解决方案
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]}`);
}
推荐阅读
- r - 使用`ggplot2::stat`时找不到`y`
- python - 如何在weakref.finalize中引用最终对象?
- javascript - 如何对齐条形中间/中心的线条标记 - 高图表
- javascript - 如何进行 javascript 回调和停止异步 - 简单示例
- sql-server - SQL Server 提取匹配子字符串的单词
- bluetooth - 使用 org.bluez.obex IF 的蓝牙类型 SMS_GSM 的 bMessage 格式
- regex - 正则表达式匹配golang中不以www开头的字符串
- java - 如何解决 Web 组件测试错误?
- php - 如何让查询生成器使用内联参数输出其原始 SQL 查询
- javascript - 执行超时功能后是否有可能注入任何东西