嘿,我正在做一些事情,但可以也不想更改 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/