使用Knockout非常简单:
HTML:
<div class="arrow-up" data-bind="click: num.upvote.bind(num)"></div>
<h5 data-bind="text: num.value, css: { pink: num.changed }">3</h5>
<div class="arrow-down" data-bind="click: num.downvote.bind(num)"></div>
脚本:
function Num(value) {
this.value = ko.observable(value);
this.changed = ko.observable(false);
}
Num.prototype.upvote = function() {
this.value(this.value()+1);
this.changed(true);
}
Num.prototype.downvote = function() {
this.value(this.value()-1);
this.changed(true);
}
var model = {
num: new Num(1),
}
ko.applyBindings(model);
看看它的实际效果:
http://jsfiddle.net/bikeshedder/UvKsz/
防止多票:
http://jsfiddle.net/bikeshedder/UvKsz/1/