点击绑定不起作用

时间:2011-09-24 19:38:08

标签: jquery templates knockout.js

我遇到click绑定问题。我正在尝试从Knockout网站运行一些示例代码,但这些代码无效。点击次数未更新。我在Firefox中没有收到任何javascript错误。有人可以帮忙吗?

这是我的代码:

<head runat="server">
    <script type="text/javascript" src="/Scripts/jquery-1.6.4.js"></script>
    <script type="text/javascript" src="/Scripts/jquery.tmpl.js"></script>  
    <script type="text/javascript" src="/Scripts/knockout-1.2.1.js"></script>
    <script type="text/javascript">
        var clickCounterViewModel = function () {
            this.numberOfClicks = ko.observable(0);

            this.registerClick = function () {
                this.numberOfClicks(this.numberOfClicks() + 1);
            }

            this.hasClickedTooManyTimes = ko.dependentObservable(function () {
                return this.numberOfClicks() >= 3;
            }, this);
        };

        ko.applyBindings(new clickCounterViewModel());
    </script>
</head>
<body>
<div>You've clicked <span data-bind="text: numberOfClicks">&nbsp;</span> times</div>

<button data-bind="click: registerClick, enable: !hasClickedTooManyTimes()">Click me</button>

<div data-bind="visible: hasClickedTooManyTimes">
    That's too many clicks! Please stop before you wear out your fingers.
    <button data-bind="click: function() { numberOfClicks(0) }">Reset clicks</button>
</div>

</body>

1 个答案:

答案 0 :(得分:2)

您希望将脚本标记移动到文档的底部,或者将其放在onload / ready函数中。在加载剩余的DOM之后,您至少需要ko.applyBindings才能执行。