【问题标题】:Filter selection where [attr!=Array]过滤器选择 [attr!=Array]
【发布时间】:2024-05-22 06:55:01
【问题描述】:

我有一个select,其中国家/地区的值为 2 个字符代码。

<select>
    <option value=""> </option>
    <option value="AF">Afghanistan</option>
    <option value="AX">Åland Islands</option>
    ...
    <option value="ZW">Zimbabwe</option>
</select>

我想禁用所有不在正在生成的数组中的选项。

var allowedCountries = ["AF", "AX", "AL", "DZ", "AS", "AD", "AO"];

有没有办法使用.filter() 来做到这一点,还是我必须遍历选项?

【问题讨论】:

    标签: jquery arrays attributes


    【解决方案1】:
    $("option").filter(function() {
        return allowed_countries.indexOf(this.value) == -1;
    }).prop('disabled', true);
    

    您可能应该将"" 放入allowedCountries,以便他们可以取消选择菜单。要么,要么过滤后重新启用它。

    【讨论】:

      【解决方案2】:

      您可以尝试将inArrayfilter 一起使用:

      $("option").filter(function (i) {
          return $.inArray(this.value, allowedCountries) == -1
      }).prop("disabled", true);
      

      演示:http://jsfiddle.net/hungerpain/cJVxC/1/

      【讨论】:

      • 其他事实 inArray 返回找到的项目的索引或 -1 而不是布尔值。以这种方式使用它会很麻烦。