You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅禁用querySelectorAll选中集合中被点击的单个按钮

解决单个按钮点击后仅禁用自身的问题

核心问题是你当前的代码在点击时会批量操作所有按钮,要实现只禁用点击的那个按钮,只需调整事件传递和按钮操作逻辑:

  1. 让计数函数接收点击的按钮元素:修改IncCounter,添加参数获取触发点击的按钮。
  2. 调整事件绑定逻辑:在绑定点击事件时,把当前按钮传给计数函数。
  3. 仅操作单个按钮:取消对所有按钮的批量禁用/启用,改为只处理点击的目标按钮。

修改后的完整代码如下:

JavaScript代码

let inc = document.querySelectorAll("[id^='incButton']");
let span = document.getElementById('countSpan');

// 页面加载时启用所有按钮
window.onload = function(){
    inc.forEach(incButton => {
        incButton.disabled = false;
    });
}

// 计数增加函数,接收点击的按钮作为参数
function IncCounter(clickedBtn){
    // 仅禁用当前点击的按钮
    clickedBtn.disabled = true;

    // 执行计数逻辑(转成数字避免字符串拼接问题)
    let count = parseInt(span.innerHTML);
    count++;
    span.innerHTML = count;

    // 750ms后重新启用当前按钮
    setTimeout(() => {
        clickedBtn.disabled = false;
    }, 750);
}

// 绑定点击事件,传递当前按钮
inc.forEach(incButton => {
    incButton.addEventListener('click', () => IncCounter(incButton));
});

HTML代码(无需修改)

<!DOCTYPE html>
<html>
    <body>
        <script type="module" src="main.js"></script>
            <span id="countSpan">0</span>
            <br>
            <button id="incButton1" disabled>increase button1</button>
            <button id="incButton2" disabled>increase button2</button>
            <button id="incButton3" disabled>increase button3</button>
            <button id="incButton4" disabled>increase button4</button>
    </body>
</html>

关键修改说明:

  • 给IncCounter添加clickedBtn参数,精准获取触发点击的按钮元素。
  • 事件监听时用箭头函数() => IncCounter(incButton),把当前循环到的按钮传递给计数函数。
  • 移除了批量操作按钮的BtnsDisable和BtnsEnable函数,改为直接对clickedBtn做禁用/启用操作。
  • 计数时用parseInt把字符串转为数字,避免出现点击后显示"01"这类字符串拼接的错误。

这样点击任意按钮时,只会禁用自身,750ms后自动恢复,其他按钮不受影响。

内容的提问来源于stack exchange,提问作者skrrts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 15:52:42