我有4个无线电输入。
当检查一个无线电时,与该无线电相关联的变量递减。取消选中时,变量应该递增。
我知道当未选中某个收音机时,没有触发更改事件,因此此处的代码无效。有没有办法实际做到这一点?
$('.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--;
}
}
});
答案 0 :(得分:0)
如果我理解你的问题,试试这个:
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语句。
这是未经测试并在手机上写的,但希望总体思路有所帮助。
干杯