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

如何选择所有type属性为number的input标签?尝试后未生效

问题描述

我想选中页面上所有带type="number"属性的<input>标签,但写的代码完全没用,还发现代码和需求根本不匹配。贴一下我写的代码:

document.getElementById("inactive").setAttribute("disabled")
}   else {
    document.getElementById('inactive').removeAttribute("disabled")
}

注:这段代码既没处理目标input,还缺了开头的if条件块,语法都不对。

解决方案

1. 正确选中所有number类型的input

要批量选这类input,用document.querySelectorAll('input[type="number"]')就行,它会返回页面上所有符合条件的元素集合(NodeList)。

2. 批量禁用/启用示例

如果你的需求是根据某个条件切换这些input的禁用状态,参考下面的代码:

// 获取所有type="number"的input
const numberInputs = document.querySelectorAll('input[type="number"]');

// 替换成你的实际判断逻辑,比如某个开关的状态
const needDisable = false;

// 遍历处理每个input
numberInputs.forEach(input => {
  // 直接操作disabled属性比用setAttribute更简洁直观
  input.disabled = needDisable;
});

原代码问题说明

你原来的代码有两个核心问题:

  • 用getElementById只能选中单个ID为inactive的元素,和选择number类型input的需求完全不沾边
  • 代码缺失开头的if(...)条件块,语法不完整,根本无法正常执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:45:14