猿问

如何使用 JS 禁用多个输入?

我试过这个


  <body>

    <input placeholder="test1" class="input"/>

    <input placeholder="test2" class="input"/>

  </body>

  <script>

       document.querySelector(".input").disabled = true;

  </script>

为什么第二个输入(test2)没有被禁用。谢谢!



慕妹3242003
浏览 137回答 3
3回答

交互式爱情

document.querySelector仅选择您搜索的第一个实例,您需要使用它document.querySelectorAll('input')来选择输入的所有实例,它返回一个您可以遍历的数组,var inputs = document.querySelectorAll('.input')for (let i = 0;i<inputs.length;i++) {&nbsp; inputs[i].disabled = true}或者使用 ForEachvar inputs = document.querySelectorAll('.input')inputs.forEach((input)=>{&nbsp; input.disabled = true})

摇曳的蔷薇

尝试查询选择器全部运行下面的代码片段:var allinputs = document.querySelectorAll('.input');for (var i = 0, len = allinputs.length; i<len; i++){    allinputs[i].disabled = true;}<input class="input"></input><input class="input"></input>

波斯汪

如果您将输入包装在<fieldset> ... </fieldset>标签中并在其上设置禁用属性<fieldset disabled>- 所有子输入都将被禁用。input:disabled {&nbsp;cursor: not-allowed;}&nbsp; <fieldset disabled>&nbsp; &nbsp; <legend>Fieldset disabled - causes all children inputs to be disabled:</legend>&nbsp; &nbsp; <label for="fname">First name:</label>&nbsp; &nbsp; <input type="text" id="fname" name="fname"><br><br>&nbsp; &nbsp; <label for="lname">Last name:</label>&nbsp; &nbsp; <input type="text" id="lname" name="lname"><br><br>&nbsp; &nbsp; <label for="email">Email:</label>&nbsp; &nbsp; <input type="email" id="email" name="email"><br><br>&nbsp; &nbsp; <label for="birthday">Birthday:</label>&nbsp; &nbsp; <input type="date" id="birthday" name="birthday"><br><br>&nbsp; &nbsp; <input type="submit" value="Submit">&nbsp; </fieldset>&nbsp;&nbsp;&nbsp; <hr/>&nbsp; &nbsp; <fieldset>&nbsp; &nbsp; <legend>Fieldset not disabled:</legend>&nbsp; &nbsp; <label for="fname">First name:</label>&nbsp; &nbsp; <input type="text" id="fname" name="fname"><br><br>&nbsp; &nbsp; <label for="lname">Last name:</label>&nbsp; &nbsp; <input type="text" id="lname" name="lname"><br><br>&nbsp; &nbsp; <label for="email">Email:</label>&nbsp; &nbsp; <input type="email" id="email" name="email"><br><br>&nbsp; &nbsp; <label for="birthday">Birthday:</label>&nbsp; &nbsp; <input type="date" id="birthday" name="birthday"><br><br>&nbsp; &nbsp; <input type="submit" value="Submit">&nbsp; </fieldset>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答