Knockout在变量而不是对象或数组上运行foreach循环

时间:2013-11-11 10:44:11

标签: javascript knockout.js

我有一个包含属性的对象。就像这个

{
    "QuestionId":31,
    "ImportanceLevel":53
}

我将ImportanceLevel绑定到div,现在我想应用应该运行的foreach循环,直到它达到ImportanceLevel的值。这是约束力。

<div data-bind="foreach:ImportanceLevel">
    <span></span>
</div>

在这里,我想生成跨度3次,我该怎么做? 如果这不是正确的方式,我认为是什么是替代方案。这会产生一些像这样的ui

enter image description here

如果等级为3,则会显示3个圆圈。

1 个答案:

答案 0 :(得分:0)

这是另一个实现相同效果的建议,没有foreach绑定。使用宽度根据重要性级别计算的div。要使其显示微小的蓝点,您可以使用背景图像。这样的事情:http://jsfiddle.net/36vLE/5/

JS:

var VM = function(){
    var self = this;
    self.importanceLevel = ko.observable(53);
    self.importanceWidth = ko.computed(function(){
       return (self.importanceLevel() * 2) + "px" 
    });
    self.increaseLevel = function(){
        self.importanceLevel(self.importanceLevel() + 10);
    }    
}

ko.applyBindings(new VM());

HTML:

<button data-bind="click:increaseLevel">increase importance</button>
<div data-bind="style:{width:importanceWidth}" id="importanceBar"></div>
<br />
<div data-bind="style:{width:importanceWidth}" id="importanceBar2"></div>