我正在尝试使用像 <!--ko if:IsShowData==true -->
这样的无容器语句 Hot Towel 模板中的 knockoutjs 但如果我使用可见绑定(bind)与某些元素(如 div)则它不会工作,那么它工作得很好。(<div data-bind="visible: IsShowData==true"></div>
)
谁能告诉我 knockoutjs 的无容器语句是否在 Hot Towel 模板中不起作用?
在默认 Hot Towel 模板中,我在 home.html 和 home.js 中添加了几行如下:
views/home.html
<section>
<h2 class="page-title" data-bind="text: title"></h2>
</section>
<!-- ko if: active()==true -->
hiiiiiiiiiiiiiii
<!--/ko-->
<div data-bind="visible: active() == true">
byeeeeeeeeeeeee
</div>
在 viewmodels/home.js 文件中
define(['services/logger'], function (logger) {
var vm = {
activate: activate,
active:ko.observable(false),
title: 'Home View'
};
return vm;
//#region Internal Methods
function activate() {
logger.log('Home View Activated', null, 'home', true);
return true;
}
//#endregion
});
我会看到 hiiiiiiiii 但我不会看到 byeeeeee
最佳答案
您的问题与 Knockout 或 if
无关contenerless 绑定(bind),但 Durandal.js(由 HotTowel 模板使用)以及 Durandal 如何处理 View 模型。
因为在 Durandal.js 中,您的viewmodel 应该只包含一个根元素,并且它会删除根级注释。
来自documentation :
The view has exactly one root element. Durandal requires this. If comments are found at the root, they will be removed. In the case where more than one root element is found, they will be wrapped in a div.
所以解决方案很简单:只需在 section
中添加两个文本即可或将所有内容包装成 div
或 section
:
<section>
<h2 class="page-title" data-bind="text: title"></h2>
<!-- ko if: active()==true -->
hiiiiiiiiiiiiiii
<!--/ko-->
<div data-bind="visible: active() == true">
byeeeeeeeeeeeee
</div>
</section>
或者
<div>
<section>
<h2 class="page-title" data-bind="text: title"></h2>
</section>
<!-- ko if: active()==true -->
hiiiiiiiiiiiiiii
<!--/ko-->
<div data-bind="visible: active() == true">
byeeeeeeeeeeeee
</div>
</div>
顺便说一句而不是if: active()==true
和 visible: active() == true
你可以简单地写:if: active
和 visible: active
关于model-view-controller - knockoutjs 的无容器语句在 hottowel SPA 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17271248/