嗨,请检查我的代码belos
<dl data-bind="foreach: MobileNos" class="morenumbeList">
<dd><a data-bind="click: $parent.delete" class="minus">-</a><span class="number" data-bind="text: mobileno"></span>
<input id="itemID" data-bind="checked: $parent.SelectPrimary,attr : { id : 'Primary_' + $index() + ''} " type="radio" name="primary"/></dd>
</dl>
我的剧本:
var mobilenoList = function (mobileno, primary) {
this.mobileno = mobileno;
this.primary = primary;
};
var MobileSave = function (mobileno, primary) {
this.mobileno = mobileno;
this.primary = primary;
}
function AppViewModel() {
var self = this;
self.MobileNos = ko.observableArray();
self.mobileno = ko.observable("");
self.primary = ko.observable(false);
self.itemID = ko.observable(0);
self.SelectPrimary = ko.computed(function () {
var mobnums = self.MobileNos();
$.each(self.MobileNos(), function (index, mobile) {
if (mobnums[index].primary) {
return true;
}
else {
return false;
}
});
})
self.MobileNos.subscribe(function () {
var mobnums = self.MobileNos();
for (var i = 0, j = mobnums.length; i < j; i++) {
var MobileNo = mobnums[i];
if (!MobileNo.index) {
MobileNo.index = ko.observable(i + 1);
} else {
MobileNo.index(i + 1);
}
}
});
$.getJSON("/User/GetContactDetails/", { UserID: $('#UserId').val() }, function (MobileNos) {
$.each(MobileNos.rows, function (index, mobnum) {
self.MobileNos.push(new mobilenoList(mobnum.mobileno, mobnum.primary));
})
});
};
$(document).ready(function () {
ko.applyBindings(new AppViewModel());
});
当我正在加载页面时,它应该是选择单选按钮,在这里我可以在“self.MobileNos”中获得正确的值,但不能根据那个检查单选按钮
修改
<input id="itemID" value="false" data-bind="checked: $parent.SelectPrimary,attr : { id : 'Primary_' + $index() + ''} " type="radio" name="primary"/></dd>
self.SelectPrimary = ko.computed(function () {
var mobnums = self.MobileNos();
$.each(self.MobileNos(), function (index, mobile) {
if (mobnums[index].primary == true) {
return "true";
}
else {
return "false";
}
});
})
答案 0 :(得分:0)
来自"checked" binding documentation:
对于单选按钮,KO将仅当前设置要检查的元素 如果参数值等于单选按钮节点的value属性 或者由checkedValue参数指定的值。
所以你需要:
radio
元素标记更改为包含value="true"
,因为如果您true
,则希望选择它。SelectPrimary
函数更改为返回字符串值"true"
或"false"
。您也可以在KnockoutJS中查看此SO question的无线电绑定
更新:
将您的SelectPrimary
更改为:
self.SelectPrimary = ko.computed(function () {
var mobnums = self.MobileNos();
var toreturn = mobnums.some(function (item) {
return item.primary == true;
});
return toreturn.toString()
})
此处的问题是误用$.each()。您返回的值仅在您的匿名函数中。换句话说,retuen值仅适用于$.each()回调,而不适用于SelectPrimary
功能。
Array.prototype.some() Browser Compatibility