首页 > 解决方案 > 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();
        }
    });`

标签: javascriptjqueryhtml

解决方案


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.


推荐阅读