0

先看看这个:

http://pastebin.com/823NMiWc

这是 Knckoutjs + Jquery Raty 插件

假设这些是数据库中的列:

story_rev: ko.observable(),
animation_rev: ko.obervable(),
sound_rev: ko.observable(),
characters_rev: ko.observable(),
enjoyment_rev: ko.observeable(),

这些基本上是数据库中基于评级的事件,范围为 0-5,步长为 0.5(数字输入)

有谁知道如何使它计算5个评级的平均值?我有点知道如何通过 jquery 做到这一点,但 knockoutjs 对我来说是另一回事。

4

1 回答 1

1

您可以使用计算出的 observable来计算平均值。

function AppViewModel() {
    var self = this;
 
    self.story_rev = ko.observable();
    self.animation_rev = ko.observable();
    self.sound_rev = ko.observable();
    self.characters_rev = ko.observable();
    self.enjoyment_rev = ko.observable();
    
    self.averageRating = ko.computed(function() {
        var ratings = [self.story_rev(), self.animation_rev(), self.sound_rev(), self.characters_rev(), self.enjoyment_rev()];
        
        return ratings.reduce(function(a, b) {
            return a + parseInt(b, 10);
        }) / ratings.length;
    });
}

var model = new AppViewModel();

model.story_rev(1);
model.animation_rev(2);
model.sound_rev(3);
model.characters_rev(4);
model.enjoyment_rev(5);

//Should output the average (in this case 3)
console.log(model.averageRating());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

于 2015-08-28T16:04:25.197 回答