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

时间:2013-05-21 23:29:10

标签: jquery twitter-bootstrap knockout.js

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

这是我正在谈论的fiddle

和一些代码:

<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);

1 个答案:

答案 0 :(得分:8)

你很亲密。我已使用解决方案更新了您的fiddle here

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>

CSS

.selected
{
    background-color:red;
}

的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);