javascript 在淘汰赛中获得选定的选项文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19562631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get selected option text in knockout
提问by Sudarshan
I am using knockoutjs to bind a select list. Here is a Sample, I want to get selected option text instead of selected value.
我正在使用knockoutjs 来绑定选择列表。这是一个示例,我想获取选定的选项文本而不是选定的值。
How to get it using knockoutjs ?
如何使用knockoutjs 获得它?
<select id="projectMenu" name="projectMenu" data-bind="
value: selectedProject,
options: projectFilters,
optionsText: 'a',
optionsValue: 'b',
optionsCaption: '-- Select Project --'
">
</select>
<b>Selected Project:</b> <span data-bind="text: selectedProject"></span>
回答by Damien
The simplest way to do it is to remove the optionsValue binding. When you don't sepcify the optionsValue binding, the entire item will be the selected value.
最简单的方法是删除 optionsValue 绑定。当您不指定 optionsValue 绑定时,整个项目将是选定的值。
<select id="projectMenu" name="projectMenu" data-bind="
value: selectedProject,
options: projectFilters,
optionsText: 'a',
optionsCaption: '-- Select Project --'
">
</select>
<b>Selected Project:
<span data-bind="text: selectedProject() ? selectedProject().a : 'no selection '"></span>
回答by Krzysztof Cieslak
As far I am concerned it is not possible with just a simple binding. But You can easily create computedObservable which choose optionText based on optionValue
就我而言,仅使用简单的绑定是不可能的。但是您可以轻松地创建基于 optionValue 选择 optionText 的计算的Observable
vm.selectedOption= ko.computed(function () {
for (var i = 0; i < this.projectFilters().length; i += 1) {
var data = this.projectFilters()[i];
if (data.a === this.selectedProject()) {
return data.b;
}
}
return null;
}, vm);
回答by user3155930
vm.selectedCountryName = ko.computed(function () {
var text = '';
ko.utils.arrayForEach(vm.countries(), function (item) {
if (item.CountryId == vm.selectedCountry()) {
text = item.CountryName;
return;
}
});
return text;
});