1

我目前正在做一个项目,我想要一个按钮来注册点击次数并在用户第一次点击按钮时显示一条消息。这是代码的样子。请帮我写代码!

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; }
4

1 回答 1

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());
});
于 2013-08-22T20:21:00.917 回答