我无法回复所选答案,但是我有一个支持每个输入值多个唯一ID的代码的增强版本。这是对我在http://drewp.quickwitretort.com/2012/09/18/0博客并在此重复:
ko.bindingHandlers.uniqueId = {
/*
data-bind="uniqueId: $data" to stick a new id on $data and
use it as the html id of the element.
data-which="foo" (optional) adds foo to the id, to separate
it from other ids made from this same $data.
*/
counter: 0,
_ensureId: function (value, element) {
if (value.id === undefined) {
value.id = "elem" + (++ko.bindingHandlers.uniqueId.counter);
}
var id = value.id, which = element.getAttribute("data-which");
if (which) {
id += "-" + which;
}
return id;
},
init: function(element, valueAccessor) {
var value = valueAccessor();
element.id = ko.bindingHandlers.uniqueId._ensureId(value, element);
},
};
ko.bindingHandlers.uniqueFor = {
/*
data-bind="uniqueFor: $data" works like uniqueId above, and
adds a for="the-new-id" attr to this element.
data-which="foo" (optional) works like it does with uniqueId.
*/
init: function(element, valueAccessor) {
element.setAttribute(
"for", ko.bindingHandlers.uniqueId._ensureId(valueAccessor(), element));
}
};
现在你可以有多个标记复选框一条记录自动IDS:
<li data-bind="foreach: channel">
<input type="checkbox" data-which="mute" data-bind="uniqueId: $data, checked: mute">
<label data-which="mute" data-bind="uniqueFor: $data">Mute</label>
<input type="checkbox" data-which="solo" data-bind="uniqueId: $data, checked: solo">
<label data-which="solo" data-bind="uniqueFor: $data">Solo</label>
</li>
我第二。但是,我是否会感到恼火,并且要求就一个稍微复杂一些的问题寻求建议 - 在那里你有一对无线电,例如,作为标签的“是”和“否”,每一个绑定回单个布尔可观察值,例如, “活跃”。此刻,所有4个元素--2个收音机和2个标签 - 都获得相同的ID。无线电对本身出现多次,所以我使用Knockout绑定为每个对生成一个唯一的名称属性,所以我需要能够将当前对的特定名称前缀到ID。 – 2012-07-16 03:55:24
您也可以使用data-bind =“attr:{for:'status_'+ $ index}”和data-bind =“attr:{id:'status_'+ $ index}”为唯一ID – viperguynaz 2013-07-26 19:14:00
您也可以使用data-bind =“attr:{for:'status_'+ $ index}”和data-bind =“attr:{id:'status_'+ $ index}”。 $ index引用当前数组项目的从零开始的索引。 $ index是一个可观察值,只要项目的索引发生更改(例如,如果将项目添加到阵列或从阵列中删除项目),它就会更新。 – viperguynaz 2013-07-26 19:27:44