如何在不使用 id 的情况下 select 我在 javascript 中的第二个单选按钮?
How to select my second radio button in javascript without using id?
嘿,我正在做一些事情,但可以也不想更改 HTML。无法添加 ID 按钮。我想 select 第二个无线电输入。
这是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 中尝试 select 的方法,但没有用:
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';
};
有人可以帮忙吗?
你真的想要 select "the second" 单选按钮,还是 select "the radio button with value 'stage'"?第二个选项听起来更具扩展性。
document.querySelector('input[type="radio"][value="stage"]')
编辑:另外,对您不使用 ID 的问题投了赞成票。总是好的做法,无论你是否被迫。
document.querySelectorAll('fieldset input[type="radio"]')[1]=function () {
document.getElementById("project").style.display = 'none';
document.getElementById("stage").style.display = 'block';
};
您可以使用 document.getElementByName
和 select 第二组:
document.getElementsByName("submit-for")[1];
用户@somethinghere 很接近,OP 选择了一个不适用于问题标题的答案,因此对于那些正在 寻找标题答案的人问题来了:
var r = document.querySelectorAll('input[type="radio"]');
if (r.item.length > 0) {console.log(r.item(1));
嘿,我正在做一些事情,但可以也不想更改 HTML。无法添加 ID 按钮。我想 select 第二个无线电输入。
这是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 中尝试 select 的方法,但没有用:
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';
};
有人可以帮忙吗?
你真的想要 select "the second" 单选按钮,还是 select "the radio button with value 'stage'"?第二个选项听起来更具扩展性。
document.querySelector('input[type="radio"][value="stage"]')
编辑:另外,对您不使用 ID 的问题投了赞成票。总是好的做法,无论你是否被迫。
document.querySelectorAll('fieldset input[type="radio"]')[1]=function () {
document.getElementById("project").style.display = 'none';
document.getElementById("stage").style.display = 'block';
};
您可以使用 document.getElementByName
和 select 第二组:
document.getElementsByName("submit-for")[1];
用户@somethinghere 很接近,OP 选择了一个不适用于问题标题的答案,因此对于那些正在 寻找标题答案的人问题来了:
var r = document.querySelectorAll('input[type="radio"]');
if (r.item.length > 0) {console.log(r.item(1));