我是knockout.js的新手并设法生成一个单选按钮列表。但我不知道如何预选列表中的第一个单选按钮。这是(我认为)代码重要部分的摘录:
knockout.js:
$.ajax({
url: '/path/to/external/rest/api/' + zipCode,
type: 'GET',
context: document.body
}).done(
function (response) {
$.each(response, function(key, droppoint) {
self.droppoints.push(droppoint);
});
}
).fail(
);
HTML:
<div data-bind="foreach: $parents[1].droppoints" >
<label>
<input class="droppoint_radio" type="radio"
name="droppoint_location"
data-bind="attr: {value: number}" />
<div class="droppoint_address">
<div data-bind="text: company_name"></div>
</div>
</label>
</div>
答案 0 :(得分:0)
您可以使用checked
绑定控制淘汰赛中的单选按钮。您可以添加表示所选单选按钮的可观察selectedPoint
,并为此可观察对象分配第一个单选按钮的值。
根据您的javascript,这可能如下所示:
viewModel.selectedPoint = ko.observable();
将checked
绑定添加到HTML:
<div data-bind="foreach: $parents[1].droppoints" >
<label>
<input class="droppoint_radio" type="radio"
name="droppoint_location"
data-bind="attr: {value: number},
checked: $parents[2].selectedPoint" />
<div class="droppoint_address">
<div data-bind="text: company_name"></div>
</div>
</label>
</div>
最后,在AJAX回调中将第一个droppoint的编号设置为默认值:
$.ajax({
url: '/path/to/external/rest/api/' + zipCode,
type: 'GET',
context: document.body
}).done(
function (response) {
$.each(response, function(key, droppoint) {
self.droppoints.push(droppoint);
});
self.selectedPoint(response[0].number);
}
)