【问题标题】:not able to get the last index inside foreach knockout.js无法获取 foreach knockout.js 中的最后一个索引
【发布时间】:2014-03-04 08:15:05
【问题描述】:

我无法在 gsp 页面的 foreach 中获取 observableArray 索引的最后一个,如下所示

<!-- ko foreach: $data.audienceInformation.IndivisualUsers -->
  <span data-bind="html:$index()"></span>        //Here index is coming correctly
  <span data-bind="html:$last"></span>           //i want last index here
  <span data-bind="html:$data+','"></span>
<!-- /ko -->

这是我的 JSON 数据

{
    "AccountMessagesHistory": {
        "audienceInformation": {
            "Accounts": ["DHL"],
            "IndivisualUsers": ["fashangxue8@163.com"]
        },
        "documentInformation": ["Name: ",
               "Title: <p>aa</p>",
               "Description: <p>aa</p>",
               "Document Type: text",
               "This document belongs (creator/last modifier) to: b2b:cpqadmin@compaq.com",
               "This document is published for the language: en_US",
               "This document was created on: Mon Mar 03 03:15:09 MST 2014",
               "This document was last modified on: Mon Mar 03 03:15:09 MST 2014",
               "This document is a text document",
               "This document will be available from: Mon Mar 03 00:00:00 MST 2014",
               "This document will be available until: Tue Mar 03 00:00:00 MST 2015",
               "This document is available under message feature card"],
        "documentHistory": ["User ID: b2b:cpqadmin@xyz.com      Name: HP Admin,ITG      Modified On: Mon Mar 03 03:15:09 MST 2014"]
    }
}

【问题讨论】:

  • 您确定您使用的是淘汰赛 2.0.0 吗?我认为 $index 直到 2.1.0 才发布

标签: knockout.js knockout-2.0 knockout-mvc


【解决方案1】:

使用数组的.length 代替$last

<span data-bind="text: ko.utils.unwrapObservable($parent.audienceInformation.IndivisualUsers).length - 1"></span>

【讨论】:

  • 要在 KO 2.1.0 中使用ko.unwrap,您需要声明它if (typeof ko.unwrap === 'undefined') { ko.unwrap = ko.utils.unwrapObservable; }
  • 你说得对,我改成ko.utils.unwrapObservable
【解决方案2】:

如果您使用的是淘汰赛 2.1.0,则可以使用:

<span data-bind="text: $parent.audienceInformation.IndivisualUsers().length - 1"></span>

<span data-bind="text: ko.utils.unwrapObservable($parent.audienceInformation.IndivisualUsers).length - 1"></span>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2018-04-07
    相关资源
    最近更新 更多