我在以下方面遇到麻烦:
当用户选择一个区域然后选择一个国家(当前功能设置为仅对澳大利亚有效)时,列表元素将隐藏并仅显示包含澳大利亚类的列表。 / p>
但是,我遇到的麻烦是,类名必须与JS中数组中的值匹配。因此,例如,美国将显示为两个类,但字符串不匹配。
用户一次只能选择一个国家/地区,但是可以将一个图像分配给多个国家/地区,并且根据所选国家/地区,仅应显示具有匹配类名的元素。
Codepen链接:https://codepen.io/Canvasandcode/pen/zMxVgm
摘要:
`$('#selectCountry').on('change', function() {
var countrySelected = $(this).val();
var brandToDisplay = "." + countrySelected;
var brandLogo = $('.brand-logo--wrapper .icon--wrapper');
console.log(countrySelected);
if (brandLogo.hasClass(countrySelected)) {
$(brandLogo).fadeOut();
$(brandToDisplay).fadeIn();
} else if ($('#selectCountry').is(':empty')) {
$(brandLogo).fadeIn();
} else {
$(brandLogo).fadeIn();
}
});`
答案 0 :(得分:0)
您可以在共享的代码段中将这些值连字符化,例如var hyphenizedCountryName = countrySelected.split(' ').join('-')
而不是countrySelected
。
$('#selectCountry').on('change', function() {
var countrySelected = $(this).val();
var hyphenizedCountryName = countrySelected.split(' ').join('-')
var brandToDisplay = "." + hyphenizedCountryName;
var brandLogo = $('.brand-logo--wrapper .icon--wrapper');
console.log(hyphenizedCountryName);
if (brandLogo.hasClass(hyphenizedCountryName)) {
$(brandLogo).fadeOut();
$(brandToDisplay).fadeIn();
} else if ($('#selectCountry').is(':empty')) {
$(brandLogo).fadeIn();
} else {
$(brandLogo).fadeIn();
}
});
因此,“美国”的console.log
是“美国”,而对于一个字词,国家/地区名称则保持不变。