【问题标题】:Show value instead of text in Knockout-bound dropdown在 Knockout-bound 下拉列表中显示值而不是文本
【发布时间】:2020-03-05 00:23:00
【问题描述】:

我有一个 HTML 下拉菜单,我在其中使用 Knockout.js 绑定选项。通过下拉菜单,您可以选择 ISO 国家/地区代码。在(短)下拉列表中,我想将两个字母的国家代码显示为文本。只有当用户打开下拉菜单时,国家的全名才会出现。比如:

+=======+===+
| DE    | v |
+=======+===+
| Germany   |
| England   |
| France    |
| Spain     |
| USA       |
+-----------+

现在,我的 HTML 代码如下所示:

<select class="form-control w-25" data-bind="
    value: customAddress.country,
    options: countryList,
    optionsText: 'name',
    optionsValue: 'code',
    optionsCaption: 'Country'
" required></select>

显然,如果您选择它,下拉列表现在会显示“德国”。我找到了一些想法,可以在 onBlur 事件中使用 jQuery 替换下拉列表的显示文本。但我担心,这会干扰敲除的数据绑定机制(所有属性都是可观察的)。

我该如何解决?我需要自定义绑定吗?

【问题讨论】:

  • 请分享您的视图模型

标签: javascript jquery html knockout.js


【解决方案1】:

您不一定需要自定义绑定处理程序(当然也不需要求助于 jQuery);这可以使用默认绑定处理程序来完成。

  1. 将选择菜单状态(打开/关闭)存储在变量中;
  2. 使用event 绑定在模糊/焦点事件上切换此变量。如果是focus 事件,我们假设菜单是打开的;如果是blur 事件,我们假设菜单已关闭。
  3. 将函数传递给optionsText,该函数将返回代码或国家/地区,具体取决于所述变量的值。

JS:

function ViewModel() {
  var vm = this;

  vm.countries = [{
      code: 'DE',
      country: 'Germany'
    },
    {
      code: 'NL',
      country: 'The Netherlands'
    },
    {
      code: 'BE',
      country: 'Belgium'
    }
  ];

  vm.countrySelectIsOpen = ko.observable(false);
  vm.selectedCountry = ko.observable();

  vm.getOptionsText = function(item) {
    return item[vm.countrySelectIsOpen() ? 'country' : 'code'];
  }

  vm.toggleCountrySelectStatus = function(data, event) {
    vm.countrySelectIsOpen(event.type === 'focus');
  }
}

ko.applyBindings(new ViewModel)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select class="form-control" data-bind="
        options: countries,
        optionsText: getOptionsText,
        optionsValue: 'code',
        optionsCaption: 'Country',
        value: selectedCountry,
        event: {
            blur: toggleCountrySelectStatus,
            focus: toggleCountrySelectStatus
        }
    "></select>

小提琴:https://jsfiddle.net/thebluenile/hf70kg84/

【讨论】:

  • 这是一个非常聪明的解决方案,我不得不说!但是,有一个轻微的缺陷:模糊事件发生在下拉菜单失去焦点时,而不是在它关闭时。这意味着,从单击条目到单击页面上的其他内容之间的时间,它仍然会显示长文本。是否有另一个事件在关闭下拉菜单后立即触发?
  • change: blurWhenSelected 添加到event: {} 绑定并在您的视图模型vm.blurWhenSelected = function(data, event) { event.currentTarget.blur(); }; 中可能会修复“轻微缺陷”:)
  • 我已经发布了一个后续问题。也许你有一个想法? stackoverflow.com/questions/60394539/…
猜你喜欢
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 2018-11-11
相关资源
最近更新 更多