我无法获得最简单的knockout.js样本吗?

时间:2013-08-23 11:42:00

标签: javascript knockout.js

我试过这段代码,但这不能正常工作。我的代码在下面

<link href="~/Content/knocktest.css" rel="stylesheet" />
    <script src="~/Scripts/knockout-2.3.0.js" type="text/javascript"></script>

<script type="text/javascript">
        $(document).ready(function () {
            var ViewModel = function (first, last) {

                this.firstName = ko.observable(first);
                this.lastName = ko.observable(last);

                this.fullName = ko.computed(function () {                  

                    return this.firstName() + " " + this.lastName();
                }, this);
            };
            ko.applyBindings(new ViewModel("Planet", "Earth"));
        });
    </script>

我的html代码

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>

1 个答案:

答案 0 :(得分:3)

你的代码没有错误,所以你唯一缺少的是你使用jQuery库的引用;

$(document).ready(function () {
    // rest of your code here
});

如果你不包含jQuery,那么你可以删除$(document).ready()代码,并确保你的JavaScript在你身体内的所有html元素之后。

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>

<span data-bind="text: firstName"></span>
<span data-bind="text: lastName"></span>

<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min.js"> </script>
<script>

    var ViewModel = function (first, last) {

        this.firstName = ko.observable(first);
        this.lastName = ko.observable(last);

        this.fullName = ko.computed(function () {
            return this.firstName() + " " + this.lastName();
        }, this);

    };
    ko.applyBindings(new ViewModel("Planet", "Earth"));

</script>

请查看此demo of your code at jsbin