我無法回覆所選答案,但是我有一個支持每個輸入值多個唯一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