淘汰嵌套的foreach绑定不起作用

时间:2013-04-03 09:09:05

标签: knockout.js

我的html为:JSfiddle

<ul data-bind="foreach: Items">
    <li data-bind="click: setTextColor, text: 'Color: ' + color"></li>
     <ul data-bind="foreach:add">
         <li data-bind="text:test"></li>
    </ul>
</ul>

和JS如下:

var Item = function(color) {
    var self = this;
    self.color = String(color);
    self.setTextColor = function(item, event) {
        console.log(item.color);
        $(event.target).css('color', color);
    };
},
     add = function (test){

        this.test = String (test);
};
ko.applyBindings(new function() {
    this.Items = ko.observableArray([
        {new Item('red'),ko.observableArray(new add('colore'),new add('is'),new add('red'))},
        {new Item('blue'),ko.observableArray(new add('colore'),new add('is'),new add('blue'))},
        {new Item('green'), ko.observableArray(new add('colore'),new add('is'),new add('green'))}
    ]);
}());

但它没有填充数据。 任何人都可以告诉我这是什么问题!!!

2 个答案:

答案 0 :(得分:1)

我会这样做:

var Item = function(color, a) {
    var self = this;
    self.color = String(color);
    self.setTextColor = function(item, event) {
        console.log(item.color);
        $(event.target).css('color', color);
    };
    self.add = ko.observableArray(ko.utils.arrayMap(a, function(item) { return new add(item); }));
},
add = function (test){
    this.test = String (test);
};
ko.applyBindings(new function() {
    this.Items = ko.observableArray([
        new Item('red',['colore','is','red']),
        new Item('blue',['colore','is','blue']),
        new Item('green', ['colore','is','green'])
    ]);
}());

JSFiddle:http://jsfiddle.net/ENQzc/

答案 1 :(得分:0)

Firebug或Chrome控制台可能吗?

SyntaxError: missing : after property id
[Stanna vid fel]  

{new Item('red'),ko.observableArray(new add('colore'),new add('is

/Wnzrr/1/show/ (line 49, col 14)

你底部的数组定义真的很奇怪,你在尝试做什么?