2012-08-04 50 views
0

我正在努力學習淘汰賽,並提出了一個問題。Knockout JS if if else to display different html based on value

我想如果子句中使用劫,但似乎無法去解決它自己

我的劇本至今看起來像

<script> 
    var SimpleListModel = function (items) { 
     this.questionType = ko.observable(""); 
     this.items = ko.observableArray(items); 
     this.itemToAdd = ko.observable(""); 
     this.addItem = function() { 
      if (this.itemToAdd() != "") { 
       var qt = $("#question-type").data("kendoDropDownList"); 
       this.questionType(qt.value()); 
       console.log(qt.value()); 
       this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update. 
       this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable 
      } 
     }.bind(this); // Ensure that "this" is always this view model 
    }; 
    $(document).ready(function() { 
     ko.applyBindings(new SimpleListModel([])); 
    }); 
</script> 

我的HTML看起來像

 <button type="submit" class="btn pull-right" data-bind="enable: itemToAdd().length > 0"><i class="icon-plus"></i>Add Question</button> 
         <div id="questions" data-bind="foreach: items"> 
          <div class="question-item"> 
           <label data-bind="text: $data" class="q-label"></label> 
           <textarea placeholder="Answer" class="q-answer"></textarea> 
           <!-- ko if: questionType()==="ABC" --> 
              Display ABC 
           <!-- /ko --> 
           <!-- ko if: questionType()==="DEF" --> 
              Display DEF 
           <!-- /ko --> 
          </div> 
          <div class="clear"></div> 
         </div> 

我需要做什麼,以獲得ko如果:questionType正常工作?

我已經更新了questionType的設置的建議,但是我正在一個錯誤Uncaught Error: Unable to parse bindings. Message: ReferenceError: questionType is not defined; Bindings value: if:questionType()==="Comment"

+0

'this.questionType = qt.value();'是不是要設置觀察到的值的有效方法。你需要傳遞新的值作爲參數:'this.questionType(qt.value());' – Tyrsius 2012-08-04 04:57:06

回答

3

由於questionType是可觀察到的,你需要調用它作爲不帶參數的函數來檢索它的值。

所以,你if語句需要看起來像:

<!-- ko if: $parent.questionType() === "ABC" --> 
    Display ABC 
<!-- /ko --> 
+0

你也想像這樣設置'this.questionType(qt.value());'。 – 2012-08-04 03:14:22

+0

Thanks guys,@RP Niemeyer我試過你的建議,但是我得到一個錯誤未捕獲的錯誤:無法解析綁定。 消息:ReferenceError:questionType未定義; 綁定值:if:questionType()===「ABC」 – 2012-08-04 03:37:00

+0

看起來您的'questionType'不在每個項目上,而是在根級別上。你的'if'塊在'items'的循環中。所以,你需要像'$ parent.questionType()'或'$ root.questionType()'或'$ root.questionType()' – 2012-08-04 10:16:18