我的JQuery点击事件中的if判断为何无法正常工作?
问题分析:工人招募判断逻辑失效的原因及修复方案
核心问题
你当前的代码中,判断foodCount >= 10的if语句仅在页面初始化时执行一次——此时foodCount的初始值是0,条件不成立,因此.worker-recruit的点击事件从未被绑定。即便后续玩家收集到足够食物,这个if语句也不会再次运行,导致招募按钮始终无响应。
修复方案
将食物数量的判断逻辑移到点击事件内部,每次用户点击招募按钮时再检查是否满足条件,而不是提前决定是否绑定事件。修改后的JavaScript代码如下:
$(document).ready(function() { // 变量初始化(建议加上let避免全局变量污染) let woodCount = 0; let stoneCount = 0; let foodCount = 0; let population = 0; let woodAdd = 1; let stoneAdd = 1; let foodAdd = 1; let populationAdd = 1; let woodWorkers = 0; let stoneWorkers = 0; let foodWorkers = 0; let unemployed = 0; $(".wood-gather").click(function() { woodCount = woodCount + woodAdd; }); $(".stone-gather").click(function() { stoneCount = stoneCount + stoneAdd; }); $(".food-gather").click(function() { foodCount = foodCount + foodAdd; }); // 关键改动:始终绑定点击事件,在事件内部判断条件 $(".worker-recruit").click(function() { if (foodCount >= 10) { population = population + 1; unemployed = unemployed + 1; foodCount = foodCount - 10; console.log(population); console.log(foodCount); console.log(unemployed); } else { // 可选:给用户提示食物不足 console.log("食物不足,无法招募工人"); } }); function CountAppend() { $("#WCount").remove(); $("#WlabelDiv").append("<label for = 'woodGather' id = 'WCount'>Wood: " + woodCount + "</label>"); $("#SCount").remove(); $("#SlabelDiv").append("<label for = 'stoneGather' id = 'SCount'>Stone: " + stoneCount + "</label>"); $("#FCount").remove(); $("#FlabelDiv").append("<label for = 'foodGather' id = 'FCount'>Food: " + foodCount + "</label>"); $("#UEM").remove(); $("#unemployedWrap").append("<p id = 'UEM'>Unemployed: " + unemployed + "</p>"); } var interval = self.setInterval(function() { CountAppend() }, 10); });
额外优化建议
- 视觉反馈优化:可以根据食物数量动态启用/禁用招募按钮,让用户更直观地知道是否可以招募:
// 在CountAppend函数里添加这段逻辑,每次更新数值时检查 if (foodCount >=10) { $(".worker-recruit").prop("disabled", false); } else { $(".worker-recruit").prop("disabled", true); } - 变量声明规范:所有变量都加上
let或const,避免隐式全局变量带来的潜在问题。
内容的提问来源于stack exchange,提问作者WebVar
相关产品推荐
相关产品推荐

