效果图,图比较简陋:
如何创建
引入knockout
<script type='text/javascript' src='http://www.see-source.com/js/knockout-2.2.0.js'></script>
Html代码
<ul data-bind='template: { name: "guideTmpl", foreach: menus }'></ul>
Js代码
<!--菜单项模板-->
<script id="guideTmpl" type="text/html">
<li >
<span data-bind='text: name, click:$root.openOrClose'></span>
<ul data-bind='template: { name: "guideTmpl", foreach: children }, visible:opened'></ul>
</li>
</script>
<script type="text/javascript">
var Menu = function(name, children, opened) {
this.name = ko.observable(name);
this.children = ko.observableArray(children || []); //下级子菜单
this.opened = ko.observable(opened); //true:展开 false:折叠
};
var PeopleModel = function() {
this.menus = ko.observableArray([
new Menu("Twitter BootStrap", [
new Menu("bootstrap介绍"),
new Menu("响应式设计"),
new Menu("JavaScript插件")
]),
new Menu("Knockout", [
new Menu("监控属性(Observables)"),
new Menu("控制流绑定(Control flow)"),
new Menu("表单域绑定(Form fields)"),
new Menu("自定义绑定(Custom)")
])
]);
//展开、折叠操作
this.openOrClose = function(source){
var opened = source.opened();
if(opened)
source.opened(false);
else
source.opened(true);
};
};
ko.applyBindings(new PeopleModel());
</script>
以上代码可直接粘贴运行