我在foreach语句中循环项目。在页面加载时,默认情况下我选择第一项(data-bind =“css:{selected:$ index()== 0}”):
var viewModel = function(){
var self = this;
self.pattern_index = 0;
self.select = function(data) {
//handle click
};
self.makes = [
{id:1, name: 'Northwoods Prestige'},
{id:2, name: 'Forest Bay'},
{id:3, name: 'Timberland'}
];
};
var model = new viewModel();
ko.applyBindings(model);
HTML:
<div class='oTitle'><span class="label label-primary">Patterns</span></div>
<div data-bind="foreach: makes">
<div data-bind="css: { selected: $index() == 0 }, click: $root.select.bind($data)">xx </div>
</div>
CSS:
.selected{background-color:red;}
我的问题是如何选择其他项目,选择点击的项目(.selected)并从第一项中删除可选择的类
答案 0 :(得分:1)
有一个可以在css绑定中使用的selectedIndex
observable来确定行是否被“选中”。
示例: http://jsfiddle.net/Lgn4ppwo/
<强> HTML 强>
<div data-bind="foreach: makes">
<div data-bind="css: { selected: $index() === $root.selectedIndex() }, click: $root.select.bind($root, $index())">xx </div>
</div>
查看模型
function ViewModel() {
this.selectedIndex = ko.observable(0);
this.select = function(index) {
this.selectedIndex(index);
};
...
};