如何用JS实现页面每次刷新随机展示不同文本与QR二维码
解决方案
问题原因
你写的随机选取内容的逻辑本身是正确的,失效的原因是qrCode函数的定义位置不对:你把函数定义放在了独立的JS片段里,但HTML加载时调用window.onload = qrCode的时候,浏览器找不到这个函数,自然不会执行随机替换的逻辑。
修复方法
把你写的JS逻辑直接放进HTML末尾的script标签即可,修改后的完整script部分如下:
// 原来的顶部栏颜色切换逻辑 function someFunction(otherName,elmnt,color) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablink"); for (i = 0; i < tablinks.length; i++) { tablinks[i].style.backgroundColor = ""; } document.getElementById(otherName).style.display = "block"; elmnt.style.backgroundColor = color; } // 触发默认打开的tab document.getElementById("defaultOpen").click(); // 随机展示内容的逻辑 const quotes = [ { quote: 'https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=text1', author: 'text1', order1: 'Order ID: #1' }, { quote: 'https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=text2', author: 'text2', order1: 'Order ID: #2' }, ] const quote = document.querySelector('.quote'); const author = document.querySelector('.author'); const order1 = document.querySelector('.order1'); function qrCode() { // 生成数组范围内的随机下标 let random = Math.floor(Math.random() * quotes.length); // 替换对应位置的内容 quote.getElementsByTagName("IMG")[0].src = quotes[random].quote; author.innerHTML = quotes[random].author; order1.innerHTML = quotes[random].order1; } // 页面加载完成后执行随机替换 window.onload = qrCode;
补充说明
- 示例里把本地图片地址换成了可直接生效的在线二维码地址,你有本地资源的话可以按自己的需求替换
- 不需要的
quote或者order1字段直接删掉对应赋值的代码行就行,不会影响其他功能 - 后续要加更多的随机内容,只要往
quotes数组里按相同格式加对象即可
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

