1

初始化时应该选择我的一个收音机(首先加载然后用户可以更改选择),但是第一次没有选择收音机,如何适当地初始化“已选择”?

这里单选“二”应该选为“已选”是真的吗?

@using (Html.BeginForm("Index", "Two", FormMethod.Post, new Dictionary<string, object> { { "data-bind", "submit:onSubmit" } }))
{

<table>
    <tr>
        <td>
            <div data-bind="foreach: items">
                <input type="radio" name="items" data-bind="attr: { value: id }, checked: $root.selected" />
                <span data-bind="text: name"></span>
            </div>
            <div data-bind="text: selected">
            </div>
        </td>
    </tr>
</table>

<input type="submit" name="send" value="Send" />
}

<script type="text/javascript">
var viewModel = {
    items: [
    { "id": 1, "name": "one", "selected": false  },
    { "id": 2, "name": "two", "selected": true },
    { "id": 3, "name": "three", "selected": false }
],
selected: ko.observable(),

    onSubmit: function(){

        var x = this.selected();

        }
    };

$(function() {
        ko.applyBindings(viewModel);
    });

</script>
4

1 回答 1

0

您需要将顶级selectedobservable设置idtrue.

就像是:

$(function() {
    var selected = ko.utils.arrayFirst(viewModel.items, function(item) {
        return item.selected; 
    });

    if (selected) {
       viewModel.selected(selected.id);   
    }

    ko.applyBindings(viewModel);
});

示例:http: //jsfiddle.net/rniemeyer/rbsZC/

于 2012-09-04T03:41:52.510 回答