我有一个州和他们的ID下拉:
<select data-bind="options: States, optionsText: 'text', value: SelectedState"></select>
的Javascript
function ViewModel() {
this.States = ko.observableArray(states);
this.SelectedState = ko.observable(usersState);
};
var states = [
{ value: 10, text: "California" },
{ value: 3, text: "New York" },
{ value: 9, text: "Florida" }
];
ko.applyBindings(new ViewModel());
usersState是一个可能包含或可能不包含用户信息的变量。默认情况下为null。但是如果用户已经登录,那么它应该填充用户选择的状态。对于此示例,用户已登录,其佛罗里达州的选择状态为9。
所以我声明usersState = 9;在顶部。
我想要做的只是根据用户信息在下拉列表中自动选择佛罗里达。
不确定为什么不选择它。这是我的小提琴:http://jsfiddle.net/neosketo/sw9dzjk1/2/
答案 0 :(得分:0)
SelectedState
指的是州对象。您的初始选择是号。您必须找到与数字对应的状态对象:
var usersState = 9;
// This method finds an object by value property
var findStateById = function(states, id) {
return states.find(function(state) {
return state.value === id;
});
};
function ViewModel() {
this.States = ko.observableArray(states);
// In this example, SelectedState is an object with a value and text property
this.SelectedState = ko.observable(findStateById(states, usersState));
};
// Test data
var states = [{
value: 10,
text: "California"
}, {
value: 3,
text: "New York"
}, {
value: 9,
text: "Florida"
}];
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: States, optionsText: 'text', value: SelectedState"></select>
(请注意,我使用了所有浏览器都不支持的Array.prototype.find
)
或者,您可以使用optionsValue
选项告诉knockout使用value
属性将选项与选项相匹配。就个人而言,我更喜欢使用实际的对象:knockout能够使用对实例的引用而不是使用字符串,这使得开发变得更容易。
var usersState = 9;
function ViewModel() {
this.States = ko.observableArray(states);
// In this example, SelectedState is a number
this.SelectedState = ko.observable(usersState);
};
var states = [{
value: 10,
text: "California"
}, {
value: 3,
text: "New York"
}, {
value: 9,
text: "Florida"
}];
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: States,
optionsText: 'text',
optionsValue: 'value',
value: SelectedState"></select>