问题
Following previous post the this code works and does the job but I am conscious this is about as DRY as the Pacific on a wet day.
I's be grateful for any suggestions that will make it more efficient.
$( "#cvl_mb_services .content-switch" ).each(function(index, el) {
var parent = $(el).parent().parent().attr("id");
var inputValue = $('#' + parent + ' input[type=radio]:checked').val();
var targetBox = '#' + parent + ' .cvl-' + inputValue + '-fields';
$(targetBox).removeClass('cvl-hide');
});
$('#cvl_mb_services .content-switch').on('click', 'input[type="radio"]', function(){
var parent = $(this).parent().parent().parent().parent().parent().parent().attr("id");
var inputValue = $(this).closest('input[type="radio"]').attr("value");
var targetBox = '#' + parent + ' .cvl-' + inputValue + '-fields';
if (inputValue == 'content') {
$('#' + parent + ' .cvl-content-fields').removeClass('cvl-hide');
$('#' + parent + ' .cvl-header-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-footer-fields').addClass('cvl-hide');
} else if (inputValue == 'header') {
$('#' + parent + ' .cvl-content-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-header-fields').removeClass('cvl-hide');
$('#' + parent + ' .cvl-footer-fields').addClass('cvl-hide');
} else if (inputValue == 'footer') {
$('#' + parent + ' .cvl-content-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-header-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-footer-fields').removeClass('cvl-hide');
}
});
回答1:
Several points to make it more DRY:
- Use only one
var
keyword, and separate the items with commas. Ex.var asdf = 1, sdfg = '', dfgh = true;
- Use multiple selectors so you apply the
.addClass
action only once. See https://api.jquery.com/multiple-selector/ - Find a way to get rid of this duplication, such as perhaps adding/using a class to select the right ancestor:
.parent().parent().parent().parent().parent().parent()
- Don't duplicate strings like
'cvl-hide'
Instead make a variable. Many JavaScript minifiers won't touch strings, so you'll end up with this duplication making your overall file larger than it needs to be. - Make variables for duplicate selectors so jQuery doesn't have to do the same lookup twice. For stuff like
$('#cvl_mb_services .content-switch')
and even for stuff like$(this)
which is duplicated.
来源:https://stackoverflow.com/questions/63035183/suggestions-to-make-this-jquery-function-more-dry-more-efficient