淘汰表:突出显示表格行

时间:2018-08-01 13:39:58

标签: javascript html knockout.js html-table knockout-3.0

我在这里有一个示例Fiddle。在此表中,我希望实现突出显示所选的特定行。如果未选中,则不应突出显示行。 我发现了Fiddle的众多示例之一,但无法将它们合并到“示例小提琴上方”中。 下面是显示基本表格的HTML代码。

<table id="devtable">
<thead>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Status</th>
    </tr>
</thead>
<tbody data-bind="foreach: items">
    <tr data-bind=" click: $parent.select  ">
        <td data-bind="text: ID"></td>
        <td data-bind="text: Name"></td>
        <td data-bind="text: Status"></td>
    </tr>
</tbody>

ID:
名称:
状态:

此处是执行操作的敲除功能

<Script>
var rowModel = function (id, name, status) {
    this.ID = ko.observable(id);
    this.Name = ko.observable(name);
    this.Status = ko.observable(status);
};

var myData = [{
    id: "001",
    name: "Jhon",
    status: "Single"
}, {
    id: "002",
    name: "Mike",
    status: "Married"
}, {
    id: "003",
    name: "Marrie",
    status: "Complicated"
}];

function MyVM(data) {
    var self = this;

    self.items = ko.observableArray(data.map(function (i) {
        return new rowModel(i.id, i.name, i.status);
    }));

    self.select = function(item) {
        self.selected(item);
        self.enableEdit(true);
    };


    self.flashCss = ko.computed(function () {
        //just an example

        return 'flash';
    });


    self.selected = ko.observable(self.items()[0]);

    self.enableEdit = ko.observable(false);

    self.changeTableData = function() {
// How do I change the Data here and it should also reflect on the Page.
// If I do binding depending on condition it gives me error
if(true){
var myData = [{
    id: "001",
    name: "Jhon",
    status: "Single"
}, {
    id: "002",
    name: "Mike",
    status: "Married"
}, {
    id: "003",
    name: "Marrie",
    status: "Complicated"
}];
}
else{
 myData = [{
    id: "111",
    name: "ABC",
    status: "Single"
}, {
    id: "222",
    name: "XYZ",
    status: "Married"
}, {
    id: "3333",
    name: "PQR",
    status: "Complicated"
}];
}
}   

}

ko.applyBindings(new MyVM(myData));
</script>

下面的CSS代码

.flash { background-color: yellow; }

1 个答案:

答案 0 :(得分:1)

您可以使用css绑定基于当前选定的值添加.flash类:

<tr data-bind="click: $parent.select, 
               css: { flash: $parent.selected() === $data }">
  ...
</tr>

如果您不喜欢在视图中定义此逻辑,则可以传递对selected可观察对象的引用,并在RowModel内创建一个计算属性:

var RowModel = function( /* ... */ selectedRow) {
  // ...
  this.isSelected = ko.pureComputed(function() {
    return selectedRow() === this;
  }, this);
}

这是您的小提琴中的快速修复方法:

http://jsfiddle.net/wa78zoe4/


P.S。如果您想要切换行为,请将select更新为:

self.select = function(item) {
  if (item === self.selected()) {
    self.selected(null);
    self.enableEdit(false);
  } else {
    self.selected(item);
    self.enableEdit(true);
  }
};