可见绑定无法正常工作

时间:2013-08-22 19:49:46

标签: javascript html knockout.js

我目前正在开展一个项目,我想要一个按钮来记录点击次数,并在用户第一次点击按钮时显示一条消息。这是代码的样子。请帮我解释一下代码!

HTML:

 <div class='liveExample'> 

 <div>Correct Answer <span data-bind='text: numberOfClicks'>&nbsp;</span> </div>

 <div>Wrong Answer <span data-bind='text: numberOfClicks'>&nbsp;</span> </div>

 <button data-bind='click: registerClick'>Click me</button>

 <div data-bind='visible: wantsExplanation'>
     That's too many clicks! Please stop before you wear out your fingers.</div>    
 </div>

 </div>

使用Javascript:

var ClickCounterViewModel = function() {
    this.numberOfClicks = ko.observable(0);
    this.wantsExplanation = ko.observable (true);

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

};

ko.applyBindings(new ClickCounterViewModel());

的CSS:

body { font-family: arial; font-size: 14px; }
.liveExample 
{ 
    padding: 1em; 
    background-color: #EEEEDD; 
    border: 1px solid #CCC; 
    max-width: 655px; 
}
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; }

1 个答案:

答案 0 :(得分:0)

只有在文档准备就绪后才应调用applyBindings

var ClickCounterViewModel = function() {
    this.numberOfClicks = ko.observable(0);
    this.wantsExplanation = ko.observable (true);

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

};

$(document).ready(function() {
     ko.applyBindings(new ClickCounterViewModel());
});