来自knockout.js视图模型的文本没有显示在html中

Text from knockout.js viewmodel not showing in html

本文关键字:显示 html 文本 js knockout 视图 模型 来自      更新时间:2023-09-26

我正在使用MVC 4玩Knockout的前端架构。我目前有以下脚本在我的前端…

<script type="text/javascript" src="~/Scripts/knockout-2.2.0.js"></script>
<script type="text/javascript" src="~/Scripts/knockout.mapping-latest.js"></script>
<script type="text/javascript">
    // This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
    function AppViewModel() {
        this.merchantName = ko.observable("Store");
    }
    // Activates knockout.js
    ko.applyBindings(new AppViewModel());
</script>

<p>Merchant name: <strong data-bind="text: merchantName"></strong></p>

问题是merchantName属性的数据没有显示在HTML中。我在Knockout教程页面http://learn.knockoutjs.com/#/?tutorial=intro上运行相同的代码一切都很好。你觉得问题出在哪里。另外,我在前端开发方面还是新手。什么是最好的方式来调试除chrome调试器以外的淘汰问题?

谢谢!

您可以使用以下2中的任何一个用于ko.applyBindings:

  1. 在DOM顶部添加document.onload检查
  2. 在DOM加载后的底部,没有任何检查

来自文档:http://knockoutjs.com/documentation/observables.html

You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery’s $ function.

只有在DOM已经加载之后才使用knockout.js。在您的示例中,只需输入

<p>Merchant name: <strong data-bind="text: merchantName"></strong></p>

放到文件的顶部

还要注意,在大多数情况下,将javascript放在</body>关闭之前是很好的做法