根据我的评论,使用 RP 绑定和修改的小提琴
ko.bindingHandlers.uniqueId = {
init: function(element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor();
var idMod = 'id-' + (allBindingsAccessor().uniqueMod || 0);
value[idMod] = value[idMod] || ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter);
element.id= value[idMod];
},
counter: 0,
prefix: "unique"
};
ko.bindingHandlers.uniqueFor = {
init: function(element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor();
var idMod = 'id-' + (allBindingsAccessor().uniqueMod || 0);
value[idMod] = value[idMod] || ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter);
element.setAttribute("for", value[idMod]);
}
};
示例使用:
<input type="radio" data-bind="checked: gender, attr: { name: 'gender-' + id() },
uniqueId: gender, uniqueMod: 'male'" value="1" />
<label data-bind="uniqueFor: gender, uniqueMod: 'male' ">Male</label>
<input type="radio" data-bind="checked: gender, attr: { name: 'gender-' + id() },
uniqueId: gender, uniqueMod: 'female'" value="2" />
<label data-bind="uniqueFor: gender, uniqueMod: 'female '">Female</label>