javascript - 如何在不使用 id 的情况下在 javascript 中选择我的第二个单选按钮?

标签 javascript input radio-button selector

嘿,我正在做一些事情,但可以也不想更改 HTML。无法添加 ID 按钮。我想选择第二个 radio 输入。

这是 html:

  <fieldset>
        <legend>I want to sign up:</legend>
        <label>
            <input type="radio" name="submit-for" value="project">
            <span>For project</span>
        </label>
        <label>
           <input type="radio" name="submit-for" value="stage">
           <span>As intern</span>
       </label>
  </fieldset>

这是我尝试在 javascript 中选择它但没有用的方法:

   document.querySelector('input[type="radio"]:nth-of-type(2)').onclick = function () {
       document.getElementById("project").style.display = 'none';
       document.getElementById("stage").style.display = 'block';
   };

   document.querySelector('input[type="radio"]:nth-child(2)').onclick = function () {
       document.getElementById("project").style.display = 'none';
       document.getElementById("stage").style.display = 'block';
   };

有人可以帮忙吗?

最佳答案

您是真的要选择“第二个”单选按钮,还是要选择“值为‘stage’的单选按钮”?第二个选项听起来更具可扩展性。

document.querySelector('input[type="radio"][value="stage"]')

编辑:另外,对您不使用 ID 的问题投赞成票。总是好的做法,无论您是否被迫这样做。

关于javascript - 如何在不使用 id 的情况下在 javascript 中选择我的第二个单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33504704/

相关文章:

javascript - 从选中的项目数组中删除特定的 id

java - 如何替换每个句子的第一个单词(来自输入文件)

Python 输入验证 - 接受正 float 或整数

css - 如何减少垂直单选按钮列表之间的间距

JavaScript - 如果选中任何复选框,则选择单选按钮

javascript - knockout : dynamic content and applyBindings

javascript - 标题 div 在水平滚动时跟随其他固定 div

c# - 如何获取单选按钮的值?

javascript - 浏览器重新格式化我的 HTML,导致不同的外观

python 只识别我输入的第一行