当我单击 e 复选框时,将出现另一个字段,一些字段将消失。为此,我编写了一个带有简单 if-else 逻辑的函数。但对于多个 if-else 逻辑,一些 block 会覆盖另一个 block 。我使用 return 但仍然无法正常工作。这是我的代码。
function checkCheckbox() {
if ($('#irregular').is(":checked")) {
$('#daysOfInactivity').show();
$("#targetPointDiv").hide();
$("#targetTransactionDiv").hide();
$("#fixedTimeDiv").hide();
$("#isNumOfTrans").hide();
return;
} else {
$('#daysOfInactivity').hide();
$("#targetPointDiv").show();
$("#targetTransactionDiv").show();
$("#fixedTimeDiv").show();
$("#isNumOfTrans").show();
return;
}
if ($('#isNumOfTrans').is(":checked")) {
$('#numOfTrans').show();
$("#targetPointDiv").hide();
$("#targetTransactionDiv").hide();
$("#fixedTimeDiv").hide();
return;
} else {
$('#numOfTrans').hide();
$("#targetPointDiv").hide();
$("#targetTransactionDiv").hide();
$("#fixedTimeDiv").hide();
return;
}
最佳答案
@ Sayed Mahmud Raihan你可以尝试这样的事情。
$(document).ready(function(){
$('#irregular').change(function(){
if ($(this).is(":checked")) {
$('#daysOfInactivity').show();
$('#targetPointDiv, #targetTransactionDiv, #fixedTimeDiv, #isNumOfTrans').hide();
} else {
$('#daysOfInactivity').hide();
$('#targetPointDiv, #targetTransactionDiv, #fixedTimeDiv, #isNumOfTrans').show();
}
});
$('#isNumOfTrans').change(function(){
if ($(this).is(":checked")) {
$('#numOfTrans').show();
$('#targetPointDiv, #targetTransactionDiv, #fixedTimeDiv').hide();
} else
$('#numOfTrans, #targetPointDiv, #targetTransactionDiv, #fixedTimeDiv').hide();
});
}
或者以这种方式-
function checkCheckBox(){
$('#irregular').change(function(){
if ($(this).is(":checked")) {
$('#daysOfInactivity').show();
$('#targetPointDiv, #targetTransactionDiv, #fixedTimeDiv, #isNumOfTrans').hide();
} else {
$('#daysOfInactivity').hide();
$('#targetPointDiv, #targetTransactionDiv, #fixedTimeDiv, #isNumOfTrans').show();
}
});
$('#isNumOfTrans').change(function(){
if ($(this).is(":checked")) {
$('#numOfTrans').show();
$('#targetPointDiv, #targetTransactionDiv, #fixedTimeDiv').hide();
} else
$('#numOfTrans, #targetPointDiv, #targetTransactionDiv, #fixedTimeDiv').hide();
});
}
$(document).ready(checkCheckBox);
或者这样-
function checkCheckBox(){
$('#irregular').change(function(){
$('#daysOfInactivity')[$(this).is(":checked")?'show':'hide'];
$('#targetPointDiv, #targetTransactionDiv, #fixedTimeDiv, #isNumOfTrans')[!($(this).is(":checked"))?'show':'hide'];
});
$('#isNumOfTrans').change(function(){
$('#numOfTrans')[(this).is(":checked")?'show':'hide'];
$('#targetPointDiv, #targetTransactionDiv, #fixedTimeDiv').hide();
});
}
$(document).ready(checkCheckBox);
关于javascript - 如何避免覆盖多个 if-else block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093660/