javascript - jQuery to filter elements with class names based on selected value
问题描述
I am having trouble with the following:
When a user selects a region, and then selects a country (currently functionality is set to only work for Australia) The list elements will hide and display only the lists that contain the class Australia.
What I'm having trouble with however is, the class name has to match the value from the array in my JS. So for example, united states would appear as two classes but the string won't match.
The user can only select one country at a time, but an image can be assigned multiple countries, and based on the country that is selected, only the elements with the matching class name should appear.
Codepen link: https://codepen.io/Canvasandcode/pen/zMxVgm
Snippet:
`$('#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();
}
});`
解决方案
You can hyphenize those values, like var hyphenizedCountryName = countrySelected.split(' ').join('-')
instead of countrySelected
in the snippet you've shared.
$('#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();
}
});
So the console.log
for "united states" is "united-states" and for one word country names it's unchanged.
推荐阅读
- api - 如何为某个帐户拉取公共帐户的 Instagram 帖子?
- javascript - 使用 jQuery 设置默认内容
- c# - 在 ubuntu 19.10 上安装 .NET 核心后无法运行示例控制台应用程序
- firebase - 使用 Firebase 扩展“导出到 BigQuery”时,导出是免费的还是作为流插入收费?
- python-3.x - 如何在 Python 中一致地导入(IDE 检查导入路径与测试运行器不同)
- mysql - 如何避免与联结表重复行。(如何使用它)?
- c++ - WinAPI - 如何将程序的所有标准输出和外部 DLL 重定向到 Win32 标准输出句柄?
- java - 比较几个项目 bij 将这些元素添加到 2 arrayList
- javascript - element.append 不适用于角度 js 中的自定义指令
- c# - WPF c# 动态对象。如何对添加的属性进行类型检查?