我希望能够设置敲除observable
的值,该值是具有case-insensitivity
的select
的value
。因此,在我下面的例子中,传递justin
会将selectedValue
设置为Justin
。
不工作:jsfiddle
工作:jsfiddle
HTML
<select id="people" data-bind="options: peopleList, value: selectedPerson, optionsCaption: 'Choose...'">
</select>
JS
function MyViewModel(defaultPerson) {
var self = this;
self.selectedPerson = ko.observable(defaultPerson);
self.peopleList = ko.observableArray(["Justin", "Sam", "Chris", "John"]);
}
$(function(){
var person = 'justin';
var viewModel = new MyViewModel(person);
ko.applyBindings(viewModel);
});
您可以自己渲染选项,而不使用options
绑定。这将允许您将值转换为小写:
<select id="people" data-bind="value: selectedPerson, optionsCaption: 'Choose...'">
<option value=''>Choose...</option>
<!-- ko foreach: peopleList -->
<option data-bind='value: $data.toLowerCase(), text: $data'></option>
<!-- /ko -->
</select>
这里是工作jsFiddle
使用optionsValue
和optionsText
绑定以"原样"呈现条目,同时保持值不区分大小写。
function MyViewModel(defaultPerson) {
var self = this;
var Person = function(name) {
this.name = name;
this.ciName = name.toLowerCase();
};
self.selectedPerson = ko.observable(defaultPerson);
self.ciSelectedPerson = ko.computed(function() {
return self.selectedPerson().toLowerCase();
});
self.peopleList = ko.observableArray(
["Justin", "Sam", "Chris", "John"].map(
function(s) { return new Person(s) }));
}
标记:
<select id="people" data-bind="options: peopleList, optionsValue: 'ciName', optionsText: 'name', value: ciSelectedPerson, optionsCaption: 'Choose...'">
</select>