简单页面无法加载KnockoutJS可观察对象

时间:2019-01-23 13:14:27

标签: javascript html knockout.js observable

我将很快处理一些使用KnockOutJS的项目,因此我将对其进行一些研究。我创建了一个包含此简单代码的简单项目(我在官方页面上找到了它),但是它不起作用。

我实际上是在复制官方示例。

<!DOCTYPE html>
<html>
<head>
    <title>KnockOut JS Test</title>
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
    <link href="/Content/site.css" rel="stylesheet"/>
    <script src="/Scripts/modernizr-2.8.3.js"></script>
    <script src="/Scripts/jquery-3.3.1.js"></script>
    <script src="/Scripts/bootstrap.js"></script>
</head>
<body>
    <script type="text/javascript" src="/Scripts/knockout-3.4.2.js">
        $(document).ready(function () {
            // Here's my data model
            var ViewModel = function (first, last) {
                this.firstName = ko.observable(first);
                this.lastName = ko.observable(last);

                this.fullName = ko.computed(function () {
                    // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
                    return this.firstName() + " " + this.lastName();
                }, this);
            };

            ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work
        }
    </script>

    <div class='liveExample'>
        <p>First name: <input data-bind='value: firstName' /></p>
        <p>Last name: <input data-bind='value: lastName' /></p>
        <h2>Hello, <span data-bind='text: fullName'> </span>!</h2>
    </div>
</body>
</html>

该页面应加载显示“你好,地球”,但仅显示“你好,”。

1 个答案:

答案 0 :(得分:2)

JS库参考标记和编写代码的实际脚本标记应该不同。将您的js代码包装在<script></script>

<!DOCTYPE html>
<html>
<head>
    <title>KnockOut JS Test</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
        $(document).ready(function () {
            // Here's my data model
            var ViewModel = function (first, last) {
                this.firstName = ko.observable(first);
                this.lastName = ko.observable(last);

                this.fullName = ko.computed(function () {
                    // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
                    return this.firstName() + " " + this.lastName();
                }, this);
            };

            ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work
        })
    </script>

    <div class='liveExample'>
        <p>First name: <input data-bind='value: firstName' /></p>
        <p>Last name: <input data-bind='value: lastName' /></p>
        <h2>Hello, <span data-bind='text: fullName'> </span>!</h2>
    </div>

</body>
</html>