JavaScript洗牌按钮点击计数器功能实现求助
实现洗牌点击计数器功能
按照你的需求,我们可以分几步把计数器功能整合到现有代码里,逻辑非常清晰:
步骤1:添加计数器显示元素
先在HTML里加个显示点击次数的区域,放在按钮上方即可:
<p>洗牌次数: <span id="shuffleCount">0</span></p>
步骤2:初始化计数器变量与更新函数
在JS代码最开头,声明全局计数器变量,再写一个专门更新页面显示的小函数,避免重复代码:
// 初始化计数器为0 let shuffleCount = 0; // 更新页面上的计数器显示 function updateCountDisplay() { document.getElementById("shuffleCount").textContent = shuffleCount; }
步骤3:修改洗牌函数
每次点击Shuffle按钮时,让计数器加1,然后调用更新函数同步页面显示:
function shuffle() { shuffleCount++; // 点击一次计数+1 updateCountDisplay(); // 更新页面显示 const copiedArr = array.map(n => n); const shuffledArray = shuffleArray(copiedArr); document.getElementById("array").innerText = printArray(shuffledArray); }
步骤4:修改重置函数
点击Restore按钮时,把计数器清零并同步页面显示:
function restore() { shuffleCount = 0; // 重置计数器 updateCountDisplay(); // 更新页面显示 document.getElementById("array").innerText = printArray(array); }
完整代码示例
修改后的HTML
<div class="container"> <span id="array"><pre></pre></span> </div> <br> <p>洗牌次数: <span id="shuffleCount">0</span></p> <br> <button onclick="shuffle()" value="randomize">Shuffle!</button> <button onclick="restore()">Restore</button>
修改后的JS
let shuffleCount = 0; function updateCountDisplay() { document.getElementById("shuffleCount").textContent = shuffleCount; } function shuffleArray(arr) { for (let i = arr.length - 1; i > 0; i--) { const r = Math.floor(Math.random() * (i + 1)); [arr[i], arr[r]] = [arr[r], arr[i]]; } return arr; }; const array = ["Apple", "Pear", "Apricot", "Nashy", "Kiwi", "Watermelon"]; function printArray(arr) { return arr.reduce((acc, n, i) => { return acc.concat(i < arr.length - 1 ? `${n}\n ` : `${n}`); }, ''); }; function shuffle() { shuffleCount++; updateCountDisplay(); const copiedArr = array.map(n => n); const shuffledArray = shuffleArray(copiedArr); document.getElementById("array").innerText = printArray(shuffledArray); } function restore() { shuffleCount = 0; updateCountDisplay(); document.getElementById("array").innerText = printArray(array); } // 初始化页面显示 restore(); updateCountDisplay();
关于页面刷新或离开的情况:因为计数器是存储在浏览器内存中的,刷新页面或关闭页面后,浏览器会自动清空这些临时变量,所以计数器会自动重置为0,不需要额外写代码处理。
内容的提问来源于stack exchange,提问作者DadManOZ
相关产品推荐
相关产品推荐

