我有一个简单的下拉列表,其中包含一些虚拟数据,每当我使用knockout从下拉列表中选择一个项目时,我想填充表格的一行。
但我有一些问题:
我已经关注了淘汰赛页面上的一些示例,但看不到如何通过下拉列表做我想做的事情。
HTML:
<h2>Add Labor to table</h2>
<select data-bind="options: optionValues"></select>
<br><br><br>
<table>
<thead><tr>
<th>Labor name</th><th></th>
</tr></thead>
<tbody data-bind="foreach: labors">
<tr>
<td data-bind="text: name"></td>
</tr>
</tbody>
</table>
JavaScript的:
// Class to represent a row in the labors grid
function LaborReservation(name) {
var self = this;
self.name = ko.observable(name);
}
// Overall viewmodel for this screen, along with initial state
function LaborsViewModel() {
var self = this;
var viewModel = { optionValues: ["Test Labor Row 1", "Test Labor Row 2", "Test Labor Row 3"]};
self.availableLabors = [{
"LaborName": "Test Labor 1"
},
{
"LaborName": "Test Labor 2"
},
{
"LaborName": "Test Labor 3"
}];
// Editable data
self.labors = ko.observableArray([
new LaborReservation("Labor Item 1"),
new LaborReservation("Labor Item 2")
]);
self.addLabors = function() {
self.labors.push(new LaborReservation(//want to add selected dropdown item
));
}
ko.applyBindings(new LaborsViewModel());
谢谢!
答案 0 :(得分:1)
您需要将select绑定到某个值,并订阅它以添加到表中。 E.g:
self.newValue = ko.observable();
self.newValue.subscribe(function(value) {
self.labors.push(new LaborReservation(value));
})
此示例完成了您要求的大部分内容: