javascript - jQuery 根据所选值过滤具有类名的元素

标签 javascript jquery html

我遇到以下问题:

当用户选择一个地区,然后选择一个国家/地区(当前功能设置为仅适用于澳大利亚)时,列表元素将隐藏并仅显示包含澳大利亚类的列表。

但是我遇到的问题是,类名必须与 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();
        }
    });`

最佳答案

您可以使用连字符连接这些值,例如在代码段中使用 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();
    }
});

因此,“united states”的 console.log 为“united-states”,而对于单字国家/地区名称,它保持不变。

关于javascript - jQuery 根据所选值过滤具有类名的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53157878/

相关文章:

html - 如何强制所有 <div> 元素在页面中具有相同的高度?

javascript - 如何仅在 jquery on() 函数不存在时设置它?

javascript - 我怎么能禁止一个词

javascript - 如何在 Angular 2 组件上添加简单的 onchange 事件

javascript - jQuery 过滤器有时会显示所有元素

javascript - 使用 jquery 删除 href 中的特定字符或标签

html - 使用 css 显示 3 个带有彼此相邻的标题的图形

javascript - 如何定义 JavaScript 中的出现次数?

javascript - 将 Google Places Autocomplete 与动态文本框结合使用

javascript - jQuery scrollLeft 不适用于 Angular