gpt4 book ai didi

javascript - JQuery 检查哪个单选按钮未被选中

转载 作者:行者123 更新时间:2023-11-28 06:37:43 25 4
gpt4 key购买 nike

我有 4 个 radio 输入。

当检查一个 radio 时,与该 radio 关联的变量会递减。取消选中时,变量应该递增。

我知道当 radio 未被选中时,不会触发更改事件,因此这里的代码将不起作用。实际上有办法做到这一点吗?

$('.radio').on('change', function() {

// if radio is checked, decrement variable associated with radio's value
if($(this).is(':checked')) {
if ($(this).val() === "int1") {
int1--;
}
if ($(this).val() === "int2") {
int2--;
}
if ($(this).val() === "int3") {
int3--;
}
if ($(this).val() === "int4") {
int4--;
}
}
// when unchecked, increment variable associated with radio's value, doesn't work!
else {
if ($(this).val() === "int1") {
int1++;
}
if ($(this).val() === "int2") {
int2++;
}
if ($(this).val() === "int3") {
int3++;
}
if ($(this).val() === "int4") {
int4--;
}
}
});

最佳答案

如果我理解你的问题,请尝试以下操作:

var whichChecked = "";
$('.radio').on('change', function() {

// if radio is checked, decrement variable associated with radio's value
if($(this).is(':checked')) {
if ($(this).val() === "int1") {
int1--;
}
if ($(this).val() === "int2") {
int2--;
}
if ($(this).val() === "int3") {
int3--;
}
if ($(this).val() === "int4") {
int4--;
}

whichChecked = $(this).val();
}
// when unchecked, increment variable associated with radio's value, doesn't work!

if (whichChecked === "int1") {
int1++;
}
if (whichChecked === "int2") {
int2++;
}
if (whichChecked === "int3") {
int3++;
}
if (whichChecked === "int4") {
int4--;
}

});

还可以考虑使用几个 switch 语句,而不是大量的 if 语句。

这未经测试并在手机上编写,但希望总体思路有所帮助。

干杯

关于javascript - JQuery 检查哪个单选按钮未被选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34124369/

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