我有一个包含以下值的复选框列表:
"AllAuctionTypes": [
{
"AuctionTypeID": "e42fde21-807c-4c81-938d-1918ca13f28b",
"AuctionTypeName": "Truck & Trailer",
"AuctionID": "00000000-0000-0000-0000-000000000000"
},
{
"AuctionTypeID": "eb1cc1c2-d08d-45b6-8c46-1dbd9d54bd35",
"AuctionTypeName": "Agriculture",
"AuctionID": "00000000-0000-0000-0000-000000000000"
},
{
"AuctionTypeID": "edb81092-0bfc-462e-a50e-4510feb54c55",
"AuctionTypeName": "Plant & Machinery",
"AuctionID": "00000000-0000-0000-0000-000000000000"
}
]
我想要对从服务器获取的数据中的已检查值进行数据绑定(bind)。看起来像这样:
{
"AuctionID": "88848ed7-c2bd-4428-9c4c-c524f2717051",
"AuctionName": "Another Auction",
"AuctionDate": "2015-04-22",
"AuctionTime": "16:50:00",
"AuctionLocation": "LolVille",
"AuctionContactPerson": "Bill",
"AuctionContactNumber": "0115552222",
"AuctionEMail": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f89a919494b8998d9b8c919796959996d69b97d68299" rel="noreferrer noopener nofollow">[email protected]</a>",
"AuctionWebsite": "http://somesite.co.za",
"AuctionType": [
{
"AuctionTypeID": "e42fde21-807c-4c81-938d-1918ca13f28b",
"AuctionTypeName": "Truck & Trailer",
"AuctionID": "00000000-0000-0000-0000-000000000000"
},
{
"AuctionTypeID": "edb81092-0bfc-462e-a50e-4510feb54c55",
"AuctionTypeName": "Plant & Machinery",
"AuctionID": "00000000-0000-0000-0000-000000000000"
}
]
}
AuctionType 值是应标记为选定的项目,但它似乎没有进行绑定(bind)。这是我的带有绑定(bind)的 HTML:
<div class="form-group">
<label>Auction Catagory</label>
<div>
<table data-bind="foreach: AllAuctionTypes">
<tr>
@*Debugging*@
<td data-bind="text: ko.toJSON($parent.Auction.AuctionType)"></td>
<td>
@*this is the segment I am trying to bind*@
<input type="checkbox" data-bind="checkedValue: $data, checked: $parent.Auction.AuctionType" /> <span data-bind="text: AuctionTypeName"></span>
</td>
</tr>
</table>
</div>
</div>
但它似乎没有根据所选内容绑定(bind)值,或者我只是错误地绑定(bind)了它。
这是屏幕截图,显示调试部分和未选中的框
任何帮助将不胜感激!
最佳答案
我按照Tyrsius的建议使用了自定义的Checked绑定(bind)。 .
复选框绑定(bind)如下所示:
<input type="checkbox" data-bind="checked: $root.IsChecked(AuctionTypeID), checkedValue: $data" /> <span data-bind="text: AuctionTypeName"></span>
我向 IsChecked 函数提供 AuctionTypeID,它会进行比较以查看哪个 ID 已被检查。
这是非常适合我的 IsChecked 函数:
self.IsChecked = function (ListID) {
var K;
var match = ko.utils.arrayFirst(self.Auction.AuctionType(), function (item) {
return ListID === item.AuctionTypeID
});
if (!match) {
K = false;
} else {
K = true;
}
return K;
}
关于javascript - KnockoutJS 复选框列表不绑定(bind)所选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29681672/