gpt4 book ai didi

javascript - 动态地,使用 for 循环检查单选按钮

转载 作者:行者123 更新时间:2023-11-28 18:56:49 25 4
gpt4 key购买 nike

我正在尝试创建一个 5 星级 radio 选择器。

这是单选按钮之一:

<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">

调用该方法并传递“3”后,这是我的 javascript 函数:

function check(stars)
{
for(i = 0 ; i < stars; i++)
{
document.getElementById("num_" + stars + "_star").checked = true;
}
}

当我运行代码时,它不会执行检查 to = true,但如果删除 for 循环,它就可以正常工作。

知道为什么 for 循环阻止检查单选框吗?

这是我的整个代码:

<script>
function check(stars)
{
for(i = 0 ; i < stars; i++)
{
document.getElementById("num_" + stars + "_star").checked = true;
}
}
</script>

<form>
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">
</form>

谢谢!

最佳答案

i had to be 1 initially as ids are starting from 1

Also reset all the checked status when click is initiated! Use i instead of stars in getElementById

试试这个:

function check(stars) {

for (var j = 1; j <= 5; j++) {
document.getElementById("num_" + j + "_star").checked = false;
}
for (var i = 1; i <= stars; i++) {
document.getElementById("num_" + i + "_star").checked = true;
}
}
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">

关于javascript - 动态地,使用 for 循环检查单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33464471/

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