【问题标题】:Iterating through the JSON at the view layer using knockout使用敲除在视图层迭代 JSON
【发布时间】:2014-05-18 17:37:14
【问题描述】:

我正在使用淘汰赛制作一个简单的网页。考虑我有以下 ViewModel 功能

self.sample_data = ko.observableArray([
  {
  1:[
        { title1:"abc", title2:"def"},
        { title1:"abc", title2:"def"}
    ],
  2:[
        { title1:"ghi", title2:"jkl"},
    ]
   }
]);

能够将key值为'1'的特定json值绑定到视图层,如下所示。

<h1 data-bind="text:sample_data[0].1[0].title1"></h1>

假设我有两个按钮“上一个”和“下一个”。单击“下一步”按钮时,我应该将 JSON 中与键值关联为“2”的数据绑定到相同的 h1 标记。我们怎样才能做到这一点?

【问题讨论】:

  • 只是一点点选择......这个问题中没有 JSON。你有一个 JavaScript 文字,而不是 JSON。 JSON 是对象的字符串表示形式。

标签: javascript json knockout.js


【解决方案1】:

您需要在视图模型中有一个可观察的索引变量。单击下一个按钮会增加该变量:

var self = {};
self.sample_data = ko.observableArray([
    {
        "1": [
            { title1: "abc11", title2: "def11" },
            { title1: "abc12", title2: "def12" }
        ],
        "2": [
            { title1: "ghi21", title2: "jkl21" }
        ]
    }
]);
self.index = ko.observable(1);
self.goToNext = function() {
    self.index(self.index() + 1);
};

然后,您的数据绑定可能如下所示:

<h1 data-bind="text: sample_data()[0][index()][0].title1"></h1>
<a data-bind="click: goToNext">Next</a>

【讨论】:

  • h1 绑定无效,sample_data 是一个 observable 并且 observable 它是一个函数,所以你必须在访问任何属性之前调用它。不要忘记ko.applyBindings(self); 这是你的sample
【解决方案2】:

您的 Json 对象的密钥无效:

JSON only allows key names to be strings

这是绑定示例

HTML

<h1 data-bind="text: sample_data()[0][2][0].title1"></h1>

JavaScript

var self = {};
self.sample_data = ko.observableArray([
  {
  "1":[
        { title1:"abc11", title2:"def11"},
        { title1:"abc12", title2:"def12"}
    ],
  "2":[
        { title1:"ghi21", title2:"jkl21"},
    ]
   }]);  

ko.applyBindings(self);

你可以玩代码here

【讨论】:

    猜你喜欢
    • 2015-05-01
    • 2015-07-20
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2014-08-01
    • 1970-01-01
    相关资源
    最近更新 更多