获取循环中项目的索引以在 if 语句中使用以获取另一个对象中的值

我试图在循环中使用当前项目的索引从父对象中获取值,如果我直接将数字放入,我只能获取数据。但是,我需要使用索引来代替.


所以 Parent 对象包含 Library、Books 和 Book prices


<!-- ko foreach: value().Library -->

      <ul>

      <li>

          <div>

               <h3 data-bind="text: Name + ' - ' +  Description"></h3>

          </div>

 <!-- ko if: $parent.value().BookPrices.length > 0  -->

          <div>

               <span data-bind="text: $parent.value().BookPrices[1].Dollars"></span>

          </div>

 <!-- /ko -->

    </li>

    </ul>

 <!-- /ko -->

任何想法/建议我如何使用循环中当前项目的索引甚至 ID 属性来使用 [ ] 获取值Dollars将不胜感激。


慕森卡
浏览 107回答 1
1回答

慕少森

是这样的吗?function ViewModel() {&nbsp; var self = this;&nbsp; self.value = ko.observable({&nbsp; &nbsp; Library: [{&nbsp; &nbsp; &nbsp; &nbsp; Id: 1,&nbsp; &nbsp; &nbsp; &nbsp; Name: 'Test 1',&nbsp; &nbsp; &nbsp; &nbsp; Description: 'Test 1 Description'&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Id: 2,&nbsp; &nbsp; &nbsp; &nbsp; Name: 'Test 2',&nbsp; &nbsp; &nbsp; &nbsp; Description: 'Test 2 Description'&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Id: 3,&nbsp; &nbsp; &nbsp; &nbsp; Name: 'Test 3',&nbsp; &nbsp; &nbsp; &nbsp; Description: 'Test 3 Description'&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ],&nbsp; &nbsp; BookPrices: [{&nbsp; &nbsp; &nbsp; Id: 1,&nbsp; &nbsp; &nbsp; Dollars: 5.99&nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; Id: 2,&nbsp; &nbsp; &nbsp; Dollars: 9.99&nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; Id: 3,&nbsp; &nbsp; &nbsp; Dollars: 15.99&nbsp; &nbsp; }]&nbsp; })&nbsp;&nbsp;&nbsp; self.getBookPrice = function(item){&nbsp; &nbsp; var result = self.value().BookPrices.filter(x=>x.Id == item.Id);&nbsp; &nbsp; return result.length === 0 ? 0.00 : result[0].Dollars;&nbsp;&nbsp;&nbsp; }}ko.applyBindings(new ViewModel());<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script><!-- ko foreach: value().Library --><ul>&nbsp; <li>&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <h3 data-bind="text: Name + ' - ' +&nbsp; Description"></h3>&nbsp; &nbsp; </div>&nbsp; &nbsp; <!-- ko if: $parent.value().BookPrices.length > 0&nbsp; -->&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <span data-bind="text: $parent.getBookPrice($data)"></span>&nbsp; &nbsp; </div>&nbsp; &nbsp; <!-- /ko -->&nbsp; </li></ul><!-- /ko -->
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript