gpt4 book ai didi

javascript - 如何在 knockout js 中使复选框的标签可点击?

转载 作者:行者123 更新时间:2023-11-30 15:47:37 24 4
gpt4 key购买 nike

我们如何使文本可点击。下面是一个被称为 knockout 模板的列表。我可以直接选中该框,但无法使文本可点击以反射(reflect)该复选框。
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

有什么方法可以让它可以点击吗?

最佳答案

放一个<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);
<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>

在你的 fiddle 中:http://jsfiddle.net/x0f1pk6q/

或者,您可以构造一个 id循环中的属性。不过,您必须绝对确保它是独一无二的。我建议您使用某种实用程序来增加闭包中的索引,保证每个 session 都是唯一的。

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

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);
<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>

关于javascript - 如何在 knockout js 中使复选框的标签可点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39831496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com