我试图ko.dataFor()
在一个select
元素上使用,但它返回了整个 ViewModel。我期望得到 selected 的对象option
,但我总是得到 ViewModel 。我试过通过select
andoption
但无论哪种方式我都会得到相同的结果。
<select id="companies" data-bind="options: companies, optionsText: 'name', optionsValue: 'id', optionsCaption: ' ' "></select>
<br/>
ko.DataFor(select)<br/>
<textarea id="a" cols="40" rows="10"></textarea>
<br/>
ko.DataFor(option)<br/>
<textarea id="b" cols="40" rows="10"></textarea>
<br/>
<div data-bind="text: ko.toJSON($root)"></div>
function MyViewModel() {
var self = this;
self.companies = ko.observableArray([{id:1, name: "Chevy"},{id:2, name: "Ford"}, {id:2, name: "Dodge"}]);
self.countries = ko.observableArray([{id:1, name: "USA"},{id:2, name: "Canada"}, {id:2, name: "Mexico"}]);
}
var vm = new MyViewModel();
ko.applyBindings(vm);
$("#companies").change(function(){
$("#a").val("dataFor("+this.id+"):"+ ko.toJSON(ko.dataFor(this)));
var selectedOption = $(this).find(":selected")[0];
$("#b").val("dataFor("+this.id+"):"+ ko.toJSON(ko.dataFor(selectedOption)));
});