如何从KO的绑定方法更改表格行背景颜色?

Ray*_*eng 4 jquery twitter-bootstrap knockout.js

我正在使用KO.js绑定一个有很多行的表体.第一列有一些按钮,如果用户点击一行按钮,我希望该行突出显示.但我不知道如何引用Ko的绑定方法中的表行.

这是我正在谈论的小提琴.

和一些代码:

<table class="table table-bordered">
    <tbody data-bind="foreach: frameworks">
        <td>
            <button class=btn data-bind="click: $parent.doStuff">A</button>
        </td>
        <td data-bind="text: $data"></td>
    </tbody>
</table>


var App = new function () {
        var self = this;
        self.frameworks = ko.observableArray();
        self.doStuff = function () {
            //how to change table row color?
        };
    };

App.frameworks.push('bootstrap');
App.frameworks.push('knockout.js');
ko.applyBindings(App);
Run Code Online (Sandbox Code Playgroud)

Rod*_*ter 8

你很亲密 我已经用解决方案更新了你的小提琴.

HTML

<table class="table table-bordered">
    <tbody data-bind="foreach: frameworks">
        <tr data-bind="css: {'selected':$root.selectedItem() == $data}">
            <td>
                <button class=btn data-bind="click: $root.doStuff">A</button>
            </td>
            <td data-bind="text: $data"></td>
        </tr>
    </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

CSS

.selected
{
    background-color:red;
}
Run Code Online (Sandbox Code Playgroud)

使用Javascript

    var App = new function () {
        var self = this;
        self.frameworks = ko.observableArray();
        self.selectedItem = ko.observable(null);
        self.doStuff = function (item) {
            self.selectedItem(item);
            //do other things here for the button click
        };
    };

    App.frameworks.push('bootstrap');
    App.frameworks.push('knockout.js');
    ko.applyBindings(App);
Run Code Online (Sandbox Code Playgroud)