我有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--;
}
}
});
如果我了解您的问题,请尝试以下操作:
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语句。
这未经测试并写在电话上,但希望总体思路有所帮助。
干杯
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句