淘汰选择标签价值神秘主义

时间:2013-05-30 10:10:27

标签: javascript knockout.js knockout-2.0

如果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);

test it in jsFiddle

如何解决此问题?

1 个答案:

答案 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