我试图学习Knockout。我想在单击行中的链接时突出显示表行。我很难理解this
,e
的背景以及淘汰赛如何与JQuery
互动。我可以像标准的jquery函数一样构建knockout函数吗?
<table>
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Cat</th>
<th>Size</th>
</tr>
</thead>
<tbody data-bind="foreach: components">
<tr>
<td></td>
<td><a data-bind="text: Name, click: $parent.highlightComponent" href="#"></a></td>
<td data-bind="text: Category"></td>
<td data-bind="text: Size"></td>
</tr>
</tbody>
</table>
然后我的视图模型......
function MyViewModel() {
this.components = ko.observableArray();
this.selectedComponent = ko.observable();
this.highlightComponent = function(e) {
console.log($(this).parents("tr"));
$(this).closest("tr").siblings().removeClass("diffColor");
$(this).parents("tr").toggleClass("diffColor", e.clicked);
}
}
答案 0 :(得分:4)
在IsHighlighted
数组中的每个项目上添加components
属性,以指示该项目是否突出显示:
this.IsHighlighted = ko.observable(false);
然后在您的HTML中,在click
上打开该属性,并将TR.diffColor
类绑定到该属性:
<tbody data-bind="foreach: components">
<tr data-bind="css: { diffColor: IsHighlighted }">
<td></td>
<td><a data-bind="text: Name, click: IsHighlighted" href="#"></a></td>
<td data-bind="text: Category"></td>
<td data-bind="text: Size"></td>
</tr>
</tbody>
<强>更新强>
根据您的请求,一次只允许一个突出显示的项目,尝试将HighlightedRowIndex
observable添加到根视图模型中:
this.HighlightedRowIndex = ko.observable();
在你的HTML中:
<tbody data-bind="foreach: components">
<tr data-bind="css: { diffColor: $root.HighlightedRowIndex() == $index }">
<td></td>
<td><a data-bind="text: Name, click: $root.HighlightedRowIndex.bind(null, $index)" href="#"></a></td>
<td data-bind="text: Category"></td>
<td data-bind="text: Size"></td>
</tr>
</tbody>