我正在使用淘汰赛 JS 开发瘦客户端,并且在单选按钮方面遇到了一些问题,希望这里的某个人能够提供一些见解,了解可能导致这种情况的原因以及我可以采取哪些措施来纠正这种情况。
我对一系列单选按钮有一个相当典型的布局。
<p data-bind="text: background().description"></p>
<div data-bind="foreach: backgroundOptions" class="bg-options">
<p data-bind="text: description" class="color-swatch"></p>
<input type="radio" name="backgroundsGroup" data-bind="checked: $parent.backgroundId, value:id"/>
</div>
您可以看到我正在绑定到父对象的 backgroundId。
父对象和正在显示的对象的 JS 如下所示:
var CardBackground = function(imagePath, swatchPath, id, description) {
var self = this;
var _imagePath = imagePath;
self.imagePath = ko.observable(_imagePath);
var _id = id;
self.id = ko.observable(_id);
var _description = description;
self.description = ko.observable(_description);
var _swatch = swatchPath;
self.swatchPath = ko.observable(_swatch);
};
var Card = function() {
var self = this;
getBackgrounds = function() {
var bgs = [
new CardBackground("noCardLarge.jpg", "card_swatch-blue.jpg", -1, "None Selected"),
new CardBackground("greenCard.jpg", "card_swatch-green.jpg", 10, "Green Contour Card"),
new CardBackground("purpleCard.jpg", "card_swatch-purple.jpg", 11, "Purple Contour Card"),
new CardBackground("redCard.jpg", "card_swatch-red.jpg", 12, "Red Contour Card"),
new CardBackground("whiteCard.jpg", "card_swatch-white.jpg", 13, "White Contour Card"),
new CardBackground("yellowCard.jpg", "card_swatch-yellow.jpg", 14, "Yellow Contour Card")
];
return bgs;
}
self.backgroundOptions = getBackgrounds();
var _defaultBackground = self.backgroundOptions[0];
self.defaultBackground = ko.observable(_defaultBackground);
var _background = self.defaultBackground();
self.background = ko.observable(_background);
self.backgroundId = ko.computed({
read: function() {
var values = self.backgroundOptions;
return values.length ? values[0] : [];
},
write: function(newValue) {
for (var i = 0; i < self.backgroundOptions.length; i++) {
if (self.backgroundOptions[i].id() == newValue) {
self.background(self.backgroundOptions[i]);
return;
}
}
},
owner: this
});
};
现在只需单击两次即可使绑定最初采取行动,然后只需单击一下即可。
此外,即使设置了默认值,也不会选择相应的选项框。如果您更改默认背景上的索引,上面的描述是正确的,但单选按钮不正确。
我已经创建了一个例子。
http://jsfiddle.net/JS2GV/2/
任何人可能有的见解将不胜感激。