3

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

<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>

4

1 回答 1

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>

在 jsbin 查看您的代码演示

于 2013-08-23T20:43:02.133 回答