【问题标题】:Visible binding is not working in knockout js可见绑定在淘汰赛 js 中不起作用
【发布时间】:2014-10-28 19:44:36
【问题描述】:

在我的代码中,我在单击添加按钮时推送一个对象,该按钮显示一个输入字段和应用按钮。单击应用按钮后,我编写了一个函数,通过该函数显示我的文本并显示字段按钮。但我收到一个错误“显示未定义” 这是我的功能

self.apply = function () {
    self.show(false);
    self.showFields(true);
};

addterm 来了

self.addTerm = function () {
    var term = new Term("12");
    self.Terms.push(term);
    self.show(true);
    self.showFields(false);
};

这里是 JS Fiddle Link

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    当您使用以下方法迭代 Terms 时:

    <tbody data-bind="foreach: Terms">
    

    tbody 内的范围成为您正在迭代的当前Term。所以当你写的时候:

    <input type="text" class="edit" data-bind="value: loanterm, visible: show"  />
    

    Knockout 正在寻找显然不存在的Term.show。因此,您需要使用 $root 关键字将 Knockout 指向根 ViewModel:

    <input type="text" class="edit" data-bind="value: loanterm, visible: $root.show"  />
    

    (同样适用于您的 showFields 属性)

    Binding-Context

    【讨论】:

      【解决方案2】:

      您需要添加父关键字。

      <button class="button addNewButton" data-bind="click: $root.addTerm">Add a new Term for Loan</button>
      <table class="termGrid">
      <thead>
          <tr>
              <th class="headRow headColumn">
                  Term
              </th>
              <th class="headRow tools">
              </th>
          </tr>
      </thead>
      <tbody data-bind="foreach: Terms">
          <tr class="row">
            <td class="tools">
      
                  <input type="text" class="edit" data-bind="value: loanterm, visible: $parent.show"  />
                  <strong class="read" data-bind="text: loanterm, visible: $parent.showFields" ></strong>
                  <a class="button toolButton" href="#" data-bind="visible: $parent.showFields" >show Tiers</a> 
                   <a class="button toolButton" href="#" data-bind="click: $root.apply,visible:$parent.show" >Apply</a> 
      
              </td>
          </tr>
      </tbody>
      

      fiddle demo

      【讨论】:

        猜你喜欢
        • 2012-11-14
        • 2018-05-21
        • 2013-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-14
        • 2013-08-14
        相关资源
        最近更新 更多