我们如何才能使文字可点击。下面是一个列表,它被称为淘汰模板。我可以直接选中该框,但无法使文本可以点击,以便它可以反映复选框。
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
有什么办法,我们可以点击它吗?
答案 0 :(得分:1)
在<label>
元素周围添加<input>
:
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;
在你的小提琴中:http://jsfiddle.net/x0f1pk6q/
或者,您可以在循环中构造id
属性。您必须绝对确定它是唯一的。我建议你使用某种实用程序来增加闭包中的索引,该闭包每个会话都保证是唯一的。
您需要使用相同的方法链接id
和for
属性:
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;