不能让knockoutjs工作

时间:2012-03-12 20:21:05

标签: javascript html knockout.js

试图第一次摆脱knockoutjs,但无法得到任何例子:

这个html页面出了什么问题 - 它只在我的浏览器中显示“名字:”/“姓氏:”:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head runat="server">
    <title>Knockout demo</title>
    <script src="Scripts/knockout-2.0.0.js" type="text/javascript"></script>
    <script type="text/javascript">
        function AppViewModel() {
            this.firstName = "Helena";
            this.lastName = "Christensen";
        }
        ko.applyBindings(new AppViewModel());
    </script>
</head>
<body>
    <div>
        <p>First name: <strong data-bind="text: firstName"></strong></p>
        <p>Last name: <strong data-bind="text: lastName"></strong></p>
    </div>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

将带有ViewModel和ko.appyBindings调用的脚本标记移动到您身体的底部。

答案 1 :(得分:0)

以下内容可行:

<html>
<head runat="server">
    <title>Knockout demo</title>
    <script src="Scripts/knockout-2.0.0.js" type="text/javascript"></script>    
</head>
<body>
    <div>
        <p>First name: <strong data-bind="text: firstName"></strong></p>
        <p>Last name: <strong data-bind="text: lastName"></strong></p>
    </div>
</body>
</html>

<script type="text/javascript">
    function AppViewModel() {
        this.firstName = "Helena";
        this.lastName = "Christensen";
    }
    ko.applyBindings(new AppViewModel());
 </script>

答案 2 :(得分:0)

或者,您可以在浏览器窗口加载所有元素后使用window.onload来触发绑定过程:

<html>
<head runat="server">
    <title>Knockout demo</title>
    <script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js" type="text/javascript"></script>    
    <script type="text/javascript">
      function AppViewModel() {
        this.firstName = "Helena";
        this.lastName = "Christensen";
      }
      window.onload = function() {
        ko.applyBindings(new AppViewModel());
      };
     </script>
</head>
<body>
    <div>
        <p>First name: <strong data-bind="text: firstName"></strong></p>
        <p>Last name: <strong data-bind="text: lastName"></strong></p>
    </div>
</body>
</html>