Knockout.js 根据数组是否为空更改可见状态
我希望仅当数组中有项目时才能显示表格。我已将我的需求简化为这个 jsfiddle 示例。
JS:
var view_model = {
lines: ko.observableArray([
{
content: 'one'},
{
content: 'two'},
{
content: 'three'},
{
content: 'four'},
]),
remove: function(data) {
view_model.lines.remove(data);
}
};
ko.applyBindings(view_model);
HTML:
<span data-bind="visible:lines">Lines Exist</span>
<ul data-bind='foreach:lines'>
<li>
<button data-bind="click:$parent.remove">
Remove
</button>
<span data-bind="text:content"></span>
</li>
</ul>
基本上我有一个网络应用程序,可以从表格中删除行。如果array.length == 0
,我想隐藏整个表格。
I want to be able to have a table show only if there are items in an array. I have simplified down my needs to this jsfiddle example.
JS:
var view_model = {
lines: ko.observableArray([
{
content: 'one'},
{
content: 'two'},
{
content: 'three'},
{
content: 'four'},
]),
remove: function(data) {
view_model.lines.remove(data);
}
};
ko.applyBindings(view_model);
HTML:
<span data-bind="visible:lines">Lines Exist</span>
<ul data-bind='foreach:lines'>
<li>
<button data-bind="click:$parent.remove">
Remove
</button>
<span data-bind="text:content"></span>
</li>
</ul>
Basically I have a web app where lines can be removed from table. If array.length == 0
, I want to hide the entire table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过多种方式做到这一点。如果lines数组没有条目,下面的小提琴使用无容器绑定来隐藏整个表。
http://jsfiddle.net/johnpapa/WLapt/4/
You can do this in several ways. The fiddle below uses the containerless bindings to hide the entire table if the lines array has no entries.
http://jsfiddle.net/johnpapa/WLapt/4/
另一个解决方案,与您最初的尝试略有不同:
Another solution, slight variation on your original attempt:
向 html 模板添加逻辑被认为是不好的做法。
我建议这个解决方案:
It is considered bad practice to add logic to the html template.
I suggest this solution:
如果你想显示这样的消息或图像jsfiddle示例
如果你想在表格行时隐藏消息数据显示成功
if you want to show message or image like this jsfiddle example
if you want to hide message when table lines datas appeared successfully