如何在淘汰赛中点击复选框的标签?

时间:2016-10-03 12:19:43

标签: javascript html knockout.js

我们如何才能使文字可点击。下面是一个列表,它被称为淘汰模板。我可以直接选中该框,但无法使文本可以点击,以便它可以反映复选框。
HTML:

<ul data-bind="template: { name: 'choiceTmpl', foreach: choices, templateOptions: { selections: selectedChoices } }"></ul>

    <script id="choiceTmpl" type="text/html">
        <li>
            <input type="checkbox" data-bind="attr: { value: $data }, checked: $item.selections" />
            <label data-bind="text: $data"></label>
        </li>
    </script>

JS:

var viewModel = {
    choices: ["one", "two", "three", "four", "five"],
    selectedChoices: ko.observableArray(["two", "four"])
};

viewModel.selectedChoicesDelimited = ko.dependentObservable(function() {
    return this.selectedChoices().join(",");
}, viewModel);

ko.applyBindings(viewModel);

Jsfiddle演示:here

有什么办法,我们可以点击它吗?

1 个答案:

答案 0 :(得分:1)

<label>元素周围添加<input>

&#13;
&#13;
var viewModel = {
  choices: ["one", "two", "three", "four", "five"],
  selectedChoices: ko.observableArray(["two", "four"])
};

viewModel.selectedChoicesDelimited = ko.dependentObservable(function() {
  return this.selectedChoices().join(",");
}, viewModel);

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

<ul data-bind="foreach: choices">
  <li>
    <label>
      <input data-bind="attr: { 
                          value: $data 
                        }, 
                        checked: $parent.selectedChoices" type="checkbox" />
      
      <span data-bind="text: $data"></span>
    </label>
  </li>
</ul>

<pre data-bind="html: JSON.stringify(selectedChoices(), null, 2)"></pre>
&#13;
&#13;
&#13;

在你的小提琴中:http://jsfiddle.net/x0f1pk6q/

或者,您可以在循环中构造id属性。您必须绝对确定它是唯一的。我建议你使用某种实用程序来增加闭包中的索引,该闭包每个会话都保证是唯一的。

您需要使用相同的方法链接idfor属性:

&#13;
&#13;
var viewModel = {
  choices: ["one", "two", "three", "four", "five"],
  selectedChoices: ko.observableArray(["two", "four"]),
  getCbId: function(val, i) {
    // This combination of value and index aims to create a 
    // "kind-of-unique" id. See answer for more info.
    return "CB_" + val + "_" + i; 
  }
};

viewModel.selectedChoicesDelimited = ko.dependentObservable(function() {
  return this.selectedChoices().join(",");
}, viewModel);

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

<ul data-bind="foreach: choices">
  <li>
    
    <input data-bind="attr: { 
                        value: $data, 
                        id: $root.getCbId($data, $index())  
                      }, 
                      checked: $root.selectedChoices" type="checkbox" />
    
    <label data-bind="text: $data, 
                      attr: { 
                        for: $root.getCbId($data, $index()) 
                      }"></label>
    
  </li>
</ul>

<pre data-bind="html: JSON.stringify(selectedChoices(), null, 2)"></pre>
&#13;
&#13;
&#13;