knockoutjs在foreach中点击可选择的项目

时间:2015-06-18 20:10:10

标签: knockout.js knockout-3.0

我在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)并从第一项中删除可选择的类

jsfiddle:http://jsfiddle.net/diegopitt/g57qs9a7/

1 个答案:

答案 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);
    };
    ...
};