У меня есть 2 изображения и два условия.
ЗАДАЧА
Если я на странице с классом тела (class), добавьте переменную htmlWrap С обновленным именем файла imgStr, чтобы показать правильную диаграмму для этой страницы.
Выпуск
Результат для imgStr не определен, поэтому он показывает URL с / undefined вместо /gi-chart-2.png. Если я перемещу переменную за пределы функции, но тогда я не смогу переключить значение переменной (имя изображения) на основе оператора if.
Код
// Check the body class
$( "body" ).each(function() {
var htmlWrap = '<div class="gi-chart-wrap"><span class="eltdf-title-holder reviews_tab ui-accordion-header ui-state-default ui-corner-all" role="tab" id="ui-id-3" aria-controls="ui-id-4" aria-selected="false" aria-expanded="false" tabindex="-1"><span class="eltdf-accordion-mark"><span class="eltdf_icon_plus icon_plus"></span><span class="eltdf_icon_minus icon_minus-06"></span></span><span class="eltdf-tab-title">GI Chart</span></span></div><div class="eltdf-accordion-content ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" id="ui-id-4" aria-labelledby="ui-id-3" role="tabpanel" aria-hidden="true" style="display: none;"><img src="/wp-content/uploads/2019/01/' +imgStr+ '" alt="GI Chart" /></div></div>';
// If the body has the class append htmlWrap with the correct imgStr variable
if ( $( this ).hasClass( "product-fruit-nuts-superfood-with-baobab" ) ) {
$( this )
var imgStr = 'gi-chart.png';
$(".eltdf-accordion-holder").each(function() {
$(this).append(htmlWrap);
});
} else if ( $( this ).hasClass( "product-dark-chocolate-mandarin" ) ) {
$( this )
var imgStr = 'gi-chart-2.png';
$(".eltdf-accordion-holder").each(function() {
$(this).append(htmlWrap)
});
}
});