How to change background color of row table from KO binding method?

I use KO.js to bind a table body with many rows. There are several buttons in the first column, if the user clicks a button on a row, I want this row to be highlighted. But I do not know how to refer to a table row from a code binding method.

here fiddle I say.

and some code:

<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); 
+4
source share
1 answer

You are close. I updated your fiddle here with a solution.

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); 
+8
source

Source: https://habr.com/ru/post/1482058/


All Articles