Knockout.js foreach在未显示的项目列表上

时间:2015-08-24 21:06:08

标签: javascript asp.net-mvc knockout.js

这不起作用

                <div data-bind="foreach:nonAdminIB">
                    <div><span data-bind="text: explanation"></span>&nbsp;</div>
                </div>

这确实显示了数据,但我对索引号进行了硬编码,我真的不知道会有多少项。

                <div><span data-bind="text: nonAdminIB[0].explanation"></span>&nbsp;</div>
                <div><span data-bind="text: nonAdminIB[1].explanation"></span>&nbsp;</div>

以下是发送到浏览器的数据

  "nonAdminIB": {
    "0": {
      "nonAdminIrregularBehaviorId": 383,
      "irregularBehaviorId": 5,
      "irregularBehaviorDescription": "Falsified Information",
      "explanation": "Falsification of information on applications/scheduling permits."
    },
    "1": {
      "nonAdminIrregularBehaviorId": 384,
      "irregularBehaviorId": 6,
      "irregularBehaviorDescription": "Falsified Score",
      "explanation": "Falsification of score information. "
    }

我如何让foreach工作?

1 个答案:

答案 0 :(得分:2)

nonAdminIB目前是一个对象,foreach仅适用于数组。

你必须将它转换为数组:

var nonAdminIBArray = [];

for(var prop in nonAdminIB) {
  if(nonAdminIB.hasOwnProperty(prop)) {
    nonAdminIBArray.push(nonAdminIB[prop]);
  }
}

然后使用nonAdminIBArray敲门。