以下將爲你做一份工作。這並不理想,但應該給你一個工作平臺。
首先,Knockout中的所有內容都與視圖模型相關聯。你希望能夠控制3個div的可見性,所以這裏有一個可能適合的視圖模型。就像我說的,不完美:)
var buttonVm = new function(){
var self = this;
// Flags for visibility
// Set first to true to cover your "first should be open" req
self.button1Visible = ko.observable(true);
self.button2Visible = ko.observable(false);
self.button3Visible = ko.observable(false);
self.toggle1 = function(){
self.button1Visible(!self.button1Visible());
}
self.toggle2 = function(){
self.button2Visible(!self.button2Visible());
}
self.toggle3 = function(){
self.button3Visible(!self.button3Visible());
}
}
你需要您的標記更改爲: -
<!-- events here. When clicked call the referenced function -->
<button type="button" data-bind="click: toggle1">Button 1</button>
<button type="button" data-bind="click: toggle2">Button 2</button>
<button type="button" data-bind="click: toggle3">Button 3</button>
<!-- Visibility set here -->
<div data-bind="visible: button1Visible"> Div 1 </div>
<div data-bind="visible: button2Visible"> Div 2 </div>
<div data-bind="visible: button3Visible"> Div 3 </div>
夫婦的事情,這裏要注意。首先,我添加了類型屬性。沒有它,按鈕的默認行爲是嘗試並提交表單。
綁了這一切: -
// Create view model
var vm = new buttonVm();
ko.applyBindings(vm);
是那些通過foreach循環對像「UserOptionVM」子視圖模型的實例呈現按鈕和相應的div,或者他們只是硬編碼? – 2012-07-19 23:38:28
該div是硬編碼的。 – StackOverflow 2012-07-23 15:35:06