使用原生JavaScript实现点击按钮随机排列展示段落功能
修改后的实现代码
1. JavaScript逻辑
你只需要把原有JS替换为下面的代码即可,原有功能完全保留,新增了随机排序逻辑:
// 预存3个源段落的内容,避免后续DOM变动导致取值错误 const sourceParas = Array.from(document.getElementsByTagName("p")).slice(0,3).map(p => p.innerHTML); const demoContainer = document.getElementById("demo"); // 随机排序数组 function shuffle(arr) { let currentIndex = arr.length, randomIndex; while (currentIndex != 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; [arr[currentIndex], arr[randomIndex]] = [arr[randomIndex], arr[currentIndex]]; } return arr; } function myFunction() { // 每次点击生成一组打乱顺序的段落 const randomParas = shuffle([...sourceParas]); // 按你原有格式拼接内容追加到容器 demoContainer.innerHTML += randomParas.join("<br><br><hr><br><br>") + "<br><br>"; }
2. HTML优化建议
你现有HTML中存在3个id="demo"的元素,id为页面唯一属性,重复id会导致JS只能选中第一个元素,建议删掉多余的2个,只保留1个用于存放生成的内容即可。
内容的提问来源于stack exchange,提问作者Daniel Levi
相关产品推荐
相关产品推荐

