knockoutjs 在 foreach 中使可选择的项目 onclick
knockoutjs make selectable items onclick within foreach
我在 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) 并从第一个项目中删除可选择的 class
jsfiddle: http://jsfiddle.net/diegopitt/g57qs9a7/
有一个 selectedIndex
可观察对象,可用于 css 绑定以确定某行是否为 "selected"。
示例: 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);
};
...
};
我在 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) 并从第一个项目中删除可选择的 class
jsfiddle: http://jsfiddle.net/diegopitt/g57qs9a7/
有一个 selectedIndex
可观察对象,可用于 css 绑定以确定某行是否为 "selected"。
示例: 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);
};
...
};