gpt4 book ai didi

javascript - 按类名选择按钮的单选按钮组

转载 作者:行者123 更新时间:2023-11-30 19:51:07 24 4
gpt4 key购买 nike

我有这段选择一组单选按钮的代码。现在,javascript 通过按 ID 获取元素来选择单选按钮。我想看看是否有办法用类名而不是 ID 来做到这一点?这里的任何帮助将不胜感激。您可以在给出的示例中看到我的代码的行为方式,我只是更愿意使用类名而不是 ID。

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="check()">Select All Option 1</button>
<button onclick="uncheck()">Un-Select Option 1</button>

<table class="table table-striped">
<thead>
<tr>
<th scope="col">Count</th>
<th scope="col">Type 1</th>
<th scope="col">Type 2</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">0</th>
<td>

<!-- Group of default radios - option 1 -->
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input allOption1" id="option1Id1" name="group1">
<label class="custom-control-label" for="option1Id1">Option 1</label>
</div>

</td>
<td>

<!-- Group of default radios - option 2 -->
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="option1Id2" name="group1" >
<label class="custom-control-label" for="option1Id2">Option 2</label>
</div>
</td>

</tr>
<tr>
<th scope="row">1</th>
<td>

<!-- Group of default radios - option 1 -->
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input allOption1" id="option2Id1" name="group2">
<label class="custom-control-label" for="option2Id1">Option 1</label>
</div>

</td>
<td>

<!-- Group of default radios - option 2 -->
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="option2Id2" name="group2" >
<label class="custom-control-label" for="option2Id2">Option 2</label>
</div>


</td>

</tr>
</tbody>
</table>




<script>
function check() {
document.getElementById("option1Id1").checked = true;
document.getElementById("option2Id1").checked = true;
/* document.getElementsByClassName('allOption1').checked = true; */
}



function uncheck() {
document.getElementById("option1Id1").checked = false;
document.getElementById("option2Id1").checked = true;
}
</script>

最佳答案

您可以使用至少两种方法之一按类名获取元素。

var elements = document.getElementsByClassName("classname");

var elements = document.querySelectorAll(".classname"); // Note the "." as this method uses CSS selectors

然后您可以遍历这些变量中的任何一个,顺便说一句,它们是 NodeList 而不是 JS Array

for(var e = 0; e < elements.length; e++) {
// do something with elements[e]
}

查看 MDN 上的文档.

关于javascript - 按类名选择按钮的单选按钮组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54449995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com