如何在HTML容器值为1及以上时启用按钮?功能实现问题
问题修复方案
核心问题分析
<a>标签不支持原生disabled属性:只有表单类元素(如<button>、<input>)才会响应disabled属性,给<a>标签添加该属性不会产生禁用效果。- 获取
<div>内容的方式错误:<div>没有.value属性,需通过.textContent或.innerText获取文本内容,且要转换为数字类型后再做判断。 - 逻辑不完整:仅处理了启用按钮的场景,未覆盖数值回到0时重新禁用按钮的逻辑。
具体修复步骤
1. 替换按钮标签(推荐方案)
将原<a>标签替换为<button>,原生支持disabled属性,无需额外CSS处理:
<button id="restart-button" class="restart-button" disabled>Cash Out</button>
若必须保留<a>标签,需通过CSS模拟禁用状态并阻止点击:
.restart-button.disabled { pointer-events: none; opacity: 0.5; cursor: not-allowed; }
后续控制按钮状态时,切换disabled类即可,而非使用原生disabled属性。
2. 修正数值获取与逻辑判断
在removeTile方法中,正确获取容器数值并完善状态控制逻辑:
Grid.prototype.removeTile = function (tile) { this.cells[tile.x][tile.y] = null; // 获取容器数值,去除空格后转换为数字 const satoshis = Number(document.querySelector(".satoshis-container").textContent.trim()); const restartBtn = document.querySelector("#restart-button"); // 根据数值状态切换按钮禁用状态 if (satoshis >= 1) { restartBtn.disabled = false; // 若用<a>标签则替换为:restartBtn.classList.remove("disabled"); } else { restartBtn.disabled = true; // 若用<a>标签则替换为:restartBtn.classList.add("disabled"); } };
3. 确保数值更新时同步触发状态判断
除removeTile外,任何修改.satoshis-container数值的场景(如新增方块、合并方块)都需触发状态判断,避免状态不同步。可将判断逻辑抽为独立函数复用:
function updateRestartButtonStatus() { const satoshis = Number(document.querySelector(".satoshis-container").textContent.trim()); const restartBtn = document.querySelector("#restart-button"); restartBtn.disabled = satoshis < 1; // <a>标签版本:restartBtn.classList.toggle("disabled", satoshis < 1); }
随后在removeTile、addTile、mergeTiles等方法中调用updateRestartButtonStatus()即可。
内容的提问来源于stack exchange,提问作者Jose Moran Urena
相关产品推荐
相关产品推荐

