如何使用knockout选中复选框的元素

时间:2017-04-07 10:10:10

标签: javascript jquery html knockout.js kendo-ui

<div id="title" data-bind="foreach: list"> 
            <input type="checkbox" data-bind="attr:{id: $index,value: list.id}" class="k-checkbox">
            <label class="k-checkbox-label" data-bind="attr:{for: $index},checked: myFunction(this),text: list.id"></label>
            </div>
            <span data-bind="text: elementsSelected"></span>
        </div>

myFunction检查我是否选中了复选框。 进入elementsSelected我想获得选择&#39; list&#39;的元素。 然后我将这个数组打印到跨度中。

1 个答案:

答案 0 :(得分:2)

您可以使用ko.pureComputed根据您的情况显示数据。

以下是一个例子:

&#13;
&#13;
var simpleListModel = function(id, item) {
  var self = this;
  self.id = ko.observable(id);
  self.item = ko.observable(item);
  self.isSelected = ko.observable(false);
  self.printItem = ko.pureComputed(function() {
    if(self.isSelected()) return self.id() + " " + self.item();
    else return "";
  }, this);
};

var masterVM = (function () {
  var self = this;      
  self.lists = ko.observableArray();
  
  for(var i = 0; i<5; i++) {
    self.lists.push(new simpleListModel(i, "Item No. " + i));
  }
})();

ko.applyBindings(masterVM); 
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div data-bind="foreach: lists">
  <div>
    <span>Check to show the item: </span>
    <input type="checkbox" data-bind="checked: isSelected" />
    <span data-bind="text: printItem"></span>
  </div>
</div>
&#13;
&#13;
&#13;