嗨朋友们,我正在尝试在 mvc razor 中的一个网页上使用 knockoutjs。从以下 ViewModel 我正在实现“添加更多”功能。但我的问题是我们如何实现以下功能:
(1) 当“烟草类型”的下拉菜单选择为“选择...”时,第二个下拉菜单应该是不可见的
(2)当我们选择一些其他值(除了“选择”)时,第二个下拉列表应该包含值 1 到 10....
(3)当我们选择“其他”而不是下拉时,应该会出现一个文本框
这是我的尝试:
<script src="@Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout-2.1.0.js")" type="text/javascript"></script>
<script type="text/html" id="ddlSelection">
<div><select></select> yrs.</div>
<div><input type="text" data-bind=""></input></div>
</script>
<div id="container">
@*<div data-bind="template:{name:'smoker'}"></div>*@
<table cellpadding="3" cellspacing="4">
<tbody data-bind="foreach: seats">
<tr>
<td>
Type of Tobacco/Nicotine consumed :
</td>
<td>
<select data-bind="options: $root.availabledrugs, value: Drug, optionsText: 'DrugName'"></select>
</td>
<td><select></select></td>
</tr>
<tr>
<td>
Quantity : <input data-bind="value: Name" />
</td>
<td>
Frequency : <select data-bind="options: $root.availablefrequency, value: Frequency, optionsText: 'frequency'"></select>
</td>
<td data-bind="text: FormatPrice"></td>
</tr>
</tbody>
</table>
<button data-bind="click:AddConsumption">Add New One</button>
</div>
<script type="text/javascript">
function setconsumption(name, initdrug,initfrequency) {
var self = this;
self.Name = name;
self.Drug = ko.observable(initdrug);
self.Frequency = ko.observable(initfrequency);
self.FormatPrice = ko.computed(function () {
return self.Drug().Price ? "$" + self.Drug().Price.toFixed(2) : "none";
});
}
function ConsumptionViewModel() {
var self = this;
self.availabledrugs = [{ "DrugName": "Choose...", "Price": 0 },
{ "DrugName": "Cigarettes", "Price": 10 },
{ "DrugName": "Cigar", "Price": 20 },
{ "DrugName": "Others", "Price": 30}];
self.availablefrequency = [{ "frequency": "Choose..." }, { "frequency": "freq1" }, { "frequency": "freq2"}];
self.seats = ko.observableArray(
[new setconsumption("", self.availabledrugs[0], self.availablefrequency[0])]);
self.AddConsumption = function () {
self.seats.push(new setconsumption("", self.availabledrugs[0], self.availablefrequency[0]));
};
}
ko.applyBindings(new ConsumptionViewModel());
</script>