Answer the question
In order to leave comments, you need to log in
How to avoid code duplication?
Hello.
There is a piece of code:
$tabsTariff.each( function() {
if ( $( this ).hasClass('b-tabs__item-title_state_current') ) {
$linkPopup.attr( 'href', '#b-popup-classic-' + $( this ).attr('data-tab-name') );
}
$( this ).on( 'click', function() {
$linkPopup.attr( 'href', '#b-popup-classic-' + $( this ).attr('data-tab-name') ); // дубль
} );
} );
$linkPopup.attr( 'href', '#b-popup-classic-' + $( this ).attr('data-tab-name') );
, even though I need to keep both the each loop and the click event? Answer the question
In order to leave comments, you need to log in
Move the repetitive parts of the code into functions with parameters, and call them when necessary. for example, in such
function setHref(item, href) {
item.attr('href', href);
}
$tabsTariff.each( function() {
var href = '#b-popup-classic-' + $( this ).attr('data-tab-name');
if ( $( this ).hasClass('b-tabs__item-title_state_current') ) {
setHref($linkPopup, href);
}
$( this ).on( 'click', function() {
setHref($linkPopup, href); // дубль
} );
} );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question