【发布时间】:2013-06-19 02:59:42
【问题描述】:
我有一个js小提琴(located here),我想用knockout.js来模仿。想法是每个按钮都有一个对应的div标签。如果相应的div标签可见,点击按钮时它应该隐藏.否则应该显示。如果其他任何不对应的div是可见的,它们应该隐藏然后显示相应的div。我如何使用knockout模仿这个jQuery版本?knockout版本的js小提琴是located here . 它可以工作,但看起来仍然很冗长。似乎应该有一种方法可以使它更加动态并减少工作量。非常感谢任何帮助。
<style type="text/css">
.text { background-color: lightgray; }
</style>
<script type="text/javascript">
$(document).ready(function () {
var viewModel = {
showHide1: ko.observable(false),
showHide2: ko.observable(false),
showHide3: ko.observable(false),
toggle1: function () {
this.showHide1(true);
this.showHide2(false);
this.showHide3(false);
},
toggle2: function () {
this.showHide1(false);
this.showHide2(true);
this.showHide3(false);
},
toggle3: function () {
this.showHide1(false);
this.showHide2(false);
this.showHide3(true);
}
};
ko.applyBindings(viewModel);
});
</script>
<div id="text1" class="text" data-bind="if: showHide1">Text 1</div>
<div id="text2" class="text" data-bind="if: showHide2">Text 2</div>
<div id="text3" class="text" data-bind="if: showHide3">Text 3</div>
<br />
<br />
<button id="button1" type="button" data-bind="click: toggle1">Button 1</button>
<button id="button2" type="button" data-bind="click: toggle2">Button 2</button>
<button id="button3" type="button" data-bind="click: toggle3">Button 3</button>
【问题讨论】:
标签: javascript jquery html binding knockout.js