如何在不刷新页面时通过点击重新赋值jQuery/JavaScript变量?
Hey there! Let's break down how to tackle your three requirements step by step. I'll put together a complete example that covers all your needs:
1. 页面加载时随机分配变量
We can create an array of your three possible values, then use Math.random() to pick one at random when the page loads. Super straightforward!
2. 点击按钮显示方块
We'll use a click event listener to toggle a CSS class that makes a hidden div visible. No fancy tricks here—just basic DOM manipulation.
3. 点击按钮重新分配变量(不刷新页面)
We'll reuse the random value function we wrote for the first step, attach it to another button's click event, and update whatever part of the page needs to show the new value.
Here's the full working code:
<!DOCTYPE html> <html> <head> <style> .hidden-square { width: 100px; height: 100px; background-color: blue; display: none; margin: 20px 0; } .show-square { display: block; } </style> </head> <body> <p>Current value: <span id="value-display"></span></p> <button id="show-square-btn">Show Square</button> <button id="reassign-btn">Reassign Variable</button> <div id="square" class="hidden-square"></div> <script> // 定义可选值数组 const possibleValues = ["Value A", "Value B", "Value C"]; let VariableVar1random; // 随机分配值的函数 function assignRandomValue() { const randomIndex = Math.floor(Math.random() * possibleValues.length); VariableVar1random = possibleValues[randomIndex]; // 更新页面显示当前值 document.getElementById("value-display").textContent = VariableVar1random; } // 页面加载时执行一次随机分配 window.addEventListener("load", assignRandomValue); // 绑定显示方块的按钮事件 document.getElementById("show-square-btn").addEventListener("click", function() { document.getElementById("square").classList.add("show-square"); }); // 绑定重新分配变量的按钮事件 document.getElementById("reassign-btn").addEventListener("click", assignRandomValue); </script> </body> </html>
代码细节说明:
- 随机变量分配: The
assignRandomValue()function usesMath.floor(Math.random() * possibleValues.length)to get a valid index for our array, then assigns the corresponding value toVariableVar1random. We call this function on page load withwindow.addEventListener("load", ...)so it runs as soon as the page is ready. - 显示方块: The square starts hidden with
display: none. When you click the "Show Square" button, we add theshow-squareclass which setsdisplay: block, making it visible instantly. - 重新分配变量: The "Reassign Variable" button triggers the same
assignRandomValue()function, so it picks a new random value without needing to refresh the page. We also update the<span>element to show the new value so you can see the change in real time.
Feel free to tweak the values, square styling, or button text to fit your exact needs!
内容的提问来源于stack exchange,提问作者Snoops

