【问题标题】:knockoutJs ko if inside foreach如果在 foreach 内,淘汰赛 ko
【发布时间】:2021-02-12 20:45:45
【问题描述】:

我有这样的事情

查看:

 <ul data-bind="foreach: colaboradores">
    <li>
      <span data-bind="text: nome"></span>
      <button
        class="btn btn-success"
        data-bind="click: $parent.show.bind($parent, $index)"
      >
      
        + Informações
      </button>
    </li>
    <!-- ko if: $parent.isDisplay -->
    <li data-bind="text: idade"></li>
    <li data-bind="text: city"></li>
    <!-- /ko -->
  </ul>

视图模型


return {
    isDisplay: ko.observable(false),

    colaboradores: ko.observableArray([
      {
        nome: 'Daniel',
        idade: 29,
        city: 'Floripa'
      },
      {
        nome: 'Iago',
        idade: 22,
        city: 'Floripa'
      },
      {
        nome: 'Rafael',
        idade: 26,
        city: 'Jaguaruna'
      }
    ]),
 
show: function ($index) {
      if (!this.isDisplay()) {
        this.isDisplay(true)
      } else if (this.isDisplay()) {
        this.isDisplay(false)
      }

      console.log(this.isDisplay())
      console.log($index)
    }

一旦我单击按钮,它就会呈现所有内容,而我只想呈现来自 foreach 中相同索引的内容。 所有三个按钮都有效,但不仅仅是显示每个“colaboradores”的内容,而是显示所有 3 个中的所有内容

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    那是因为你只有一个 isDisplay 变量。

    一种可能的解决方案是使用数组来跟踪您要显示的项目。

    return {
        displayItems: ko.observableArray(),
    
        colaboradores: ko.observableArray([
          {
            nome: 'Daniel',
            idade: 29,
            city: 'Floripa'
          },
          {
            nome: 'Iago',
            idade: 22,
            city: 'Floripa'
          },
          {
            nome: 'Rafael',
            idade: 26,
            city: 'Jaguaruna'
          }
        ]),
     
        toggleItem: function ($index) {
            var index = this.displayItems.indexOf($index);
            if (index > -1) {
                this.displayItems.splice(index, 1);
            } else {
                this.displayItems.push($index);
            }
        }
    }
    

    你的 HTML 应该是这样的:

     <ul data-bind="foreach: colaboradores">
        <li>
          <span data-bind="text: nome"></span>
          <button
            class="btn btn-success"
            data-bind="click: $parent.toggleItem.bind($parent, $index)"
          >
          
            + Informações
          </button>
        </li>
        <!-- ko if: $parent.displayItems.indexOf($index) > -1 -->
        <li data-bind="text: idade"></li>
        <li data-bind="text: city"></li>
        <!-- /ko -->
      </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-28
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 2014-12-11
      • 2015-05-28
      相关资源
      最近更新 更多