如果Knockout的文本表示相等的选项文本,则不会创建值属性。所以选择的值神秘地转换为字符串类型:
<select data-bind="foreach: opts, value: val">
<option data-bind="text: name, value: id"></option>
</select>
var vm = {
opts: [{id: 1, name: 'a'}, {id: 2, name: '2'}],
val: ko.observable(1)
};
vm.val.subscribe(function (x) {
console.log(x, typeof x);
});
ko.applyBindings(vm);
如何解决此问题?
答案 0 :(得分:2)
options binding会保留您的类型。例如:
<select data-bind="value: val, options: opts, optionsText: 'name', optionsValue: 'id'"></select>
<script src="knockout.js"></script>
<script>
var vm = {
opts: [{id: 1, name: 'a'}, {id: 2, name: '2'}],
val: ko.observable(1)
};
vm.val.subscribe(function (x) {
console.log(x, typeof x);
});
ko.applyBindings(vm);
</script>
输出:
2 number
1 number