隐藏列的一部分并通过用 knockout 使鼠标悬停时显示它
2017-09-29
599
我有一张表:
table class="table">
<thead>
<tr>
<th>ID</th>
<th>Description</th>
</tr>
</thead>
<tbody data-bind="foreach: Curriculums">
<tr>
<td data-bind="text: ID"></td>
<td>
<div data-bind="event: { mouseover: toggle, mouseout: toggle }>
<span data-bind="text: curCode"></span>
</div>
<div data-bind="visible: selected">
<span data-bind="text: curDescription"></span>
</div>
</td>
</tr>
</tbody>
</table>
这是我的 knockout js
var Vm =
{
Curriculums: ko.observableArray([]),
ID: ko.Observable(),
curCode: ko.observable(),
curDescription: ko.observable(),
selected: ko.observable(false),
toggle: function() {
this.selected(!this.selected());
}
}
我正在尝试加载课程表的所有记录。我成功检索了它并在没有鼠标悬停/移出绑定的情况下显示了它。问题是当我实现鼠标悬停和鼠标移出绑定时,knockout 会抛出一个错误:
Uncaught Error: Unable to parse bindings.
Message: ReferenceError: toggle is not defined;
Bindings value: event: { mouseover: toggle}
我该如何让它工作?如果鼠标没有悬停,我会隐藏 curDescription 跨度,并在鼠标悬停到 curCode 跨度时使其重新出现
2个回答
toggle
应以
$parent
作为前缀,因为您在
foreach
绑定中使用它。否则 knockout 将在
Curriculums
数组中的每个项目内查找该函数。
<tbody data-bind="foreach: Curriculums">
<tr>
<td data-bind="text: ID"></td>
<td>
<div data-bind="event: { mouseover: $parent.toggle, mouseout: $parent.toggle }>
<span data-bind="text: curCode"></span>
</div>
<div data-bind="visible: selected">
<span data-bind="text: curDescription"></span>
</div>
</td>
</tr>
</tbody>
这仍然不会给您预期的结果。
ID
、
curCode
、
selected
和
curDescription
应为
Curriculums
数组中项目的属性。您不需要在
Vm
中使用它。
var Vm = {
Curriculums: ko.observableArray([{
ID: 1,
curCode: "CS101",
curDescription: "Why C#?",
selected: ko.observable(false) // this needs to be an observable
}, {
ID: 2,
curCode: "CS102",
curDescription: "Javascript 101",
selected: ko.observable(false)
}]),
// "item" will have the current "Curriculum" element which triggered the event
toggle: function(item) {
item.selected(!item.selected());
}
}
这里有一个 fiddle 供您测试。阅读 knockout 文档并尝试一些 fiddle,以更好地理解 ko 绑定。
正如另一个问题的
answer
中所述,您可以通过纯
CSS
实现这一点。但同样,了解绑定在
foreach
中的工作方式非常重要。
adiga
2017-09-29
我个人我只是求助于CSS,这是一件简单的事情,尤其是因为它更像是一个视觉内容,而不是程序逻辑:
354199371
css:
531888778
但是,这是一种替代方法,不是真正的解释 为什么您的解决方案不起作用。这里发布的另一个答案在解释这一点方面做得很好。
Balázs
2017-09-30