有沒有辦法將數組元素作爲輸入或選擇的值綁定?數據綁定數組元素作爲值使用敲除
事情是這樣的......
var ViewModel = function() {
var self = this;
self.array = ko.observableArray([undefined, undefined, undefined]);
self.text = ko.computed(function() {
return self.array()[0] + self.array()[1] + self.array()[2];
});
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input data-bind="value: $root.array[0]" />
<input data-bind="value: $root.array[1]" />
<input data-bind="value: $root.array[2]" />
<p data-bind="text: $root.text"></p>
編輯
對不起球員,我真的很可怕,使問題,但我的問題是有點更靠譜,我的真實條目是選擇,它是一個數組的過濾器並選擇了這些值。像這樣:
var ViewModel = function() {
var self = this;
self.family = ko.mapping.fromJS(data.family);
self.array = ko.observableArray([ko.observable(undefined), ko.observable(undefined), ko.observable(undefined)]);
self.filterFamily1 = function() {
return self.family().filter(function(i) {
return i.parent() == null;
});
}
self.filterFamily2 = ko.computed(function() {
return ko.utils.arrayFilter(self.family, function(i) {
return i.parent() === self.array()[0]().name();
});
});
self.filterFamily3 = ko.computed(function() {
return ko.utils.arrayFilter(self.family, function(i) {
return i.parent() === self.array()[1]().name();
});
})
}
var data = {
family: [{
name: "John",
parent: null
}, {
name: "Mary",
parent: null
}, {
name: "Erick",
parent: "John"
}, {
name: "Paul",
parent: "John"
}, {
name: "Marshall",
parent: "Mary"
}, {
name: "Ross",
parent: "Paul"
}]
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<select data-bind="options: $root.filterFamily1(),optionsText: 'name', value: $root.array()[0]"></select>
<select data-bind="options: $root.filterFamily2(),optionsText: 'name', value: $root.array()[1]"></select>
<select data-bind="options: $root.filterFamily3(),optionsText: 'name', value: $root.array()[2]"></select>
但答案是正確的,我之前說明問題。
非常感謝,它的工作原理。 – Guto