我有一个 HTML 下拉列表,我在其中使用 Knockout.js 绑定(bind)选项。通过下拉列表,您可以选择 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 替换下拉列表的显示文本的想法。但我担心,这会干扰 knockout 的数据绑定(bind)机制(所有属性都是可观察的)。
我该如何解决这个问题?我需要自定义绑定(bind)吗?
最佳答案
您不一定需要自定义绑定(bind)处理程序(当然也不需要诉诸 jQuery);这可以使用默认绑定(bind)处理程序来完成。
- 将选择菜单状态(打开/关闭)存储在变量中;
- 使用
event
绑定(bind)在模糊/焦点事件上切换此变量。如果它是一个focus
事件,我们假设菜单是打开的;如果是blur
事件,我们假设菜单已关闭。 - 将一个函数传递给
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>
关于javascript - 在 knockout 绑定(bind)的下拉列表中显示值而不是文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58765367/