在 jQuery 中,是否可以存储通配符以供函数中进一步使用?

In jQuery, Is it possible to store a wildcard for further use in a function?

例如,如果我有 4 个按钮和 div,例如:

<button class="country-denmark"></button>
<button class="country-denmark"></button>
<button class="country-germany"></button>
<button class="country-norway"></button>

<div class="country-denmark"></div>
<div class="country-denmark"></div>
<div class="country-germany"></div>
<div class="country-norway"></div>

在 jQuery 中,我有一个带有通配符选择器的点击功能,如下所示:

$("button[class^='country-']").on('click', function() {
  // Add class to divs that match the wildcard of this
  $("div[class^='country-']").addClass( className );
});

如果我单击带有 class country-germany 的按钮,我如何只存储“德国”部分然后找到匹配相同的 div(s)通配符?

我会选择 sessionStorage

但我也会对元素进行一些更新,以便更直接地获得预期值:

<button class="country-denmark" data-for="denmark"></button>
<button class="country-denmark" data-for="denmark"></button>
<button class="country-germany" data-for="germany"></button>
<button class="country-norway" data-for="norway"></button>

<div class="country-denmark" data-country="denmark"></div>
<div class="country-denmark" data-country="denmark"></div>
<div class="country-germany" data-country="germany"></div>
<div class="country-norway" data-country="norway"></div>

从这里您只需在 sessionStorage 中设置项目:

$("button[class^='country-']").on('click', function() {
    let country = $(this).data("for");

    let selectedCountry;

    $("div").each(function() {
        if ($(this).data("country") == country) {
            selectedCountry = $(this).data("country");
        }
    });

    sessionStorage.setItem("selectedCountry", selectedCountry);
});

要稍后读取值,请使用 sessionStorage.getItem()

var selectedCountry = sessionStorage.getItem("selectedCountry");

我已经有一段时间没有接触 jQuery,但如果我没记错的话,您可以使用 jQuery-this

$("button[class^='country-']").on('click', function() {
  // Add class to divs that match the wildcard of this
  const className = $(this).attr('class')
  $(`div.${className}`).addClass( className );
});