如何确保在knockout js的下拉列表中选择特定值作为默认值

how to ensure a specific value is selected as default value in a drop downlist in knockoutjs

我想要得到的是 'Another test' 而不是 'test' 作为下拉列表中的默认值(在页面加载时选择)。

在简单的情况下 as shown here 这很容易..但是当你有如下嵌套结构时..该怎么办..

我的html:

  <div data-bind="with:g">

            <div><input type="text" class="form-control" data-bind="value: gname" /></div>

            <div>
                <table>

                    <tbody>
                        <tr data-bind="with:gdetails">
                            <td>
                                <select data-bind="options: eventschemas, optionsText: 'schema', value:eventschemacondition().schema, event: {change:eventschemacondition().setschema}"></select>

                            </td>

                        </tr>
                    </tbody>
                </table>
                <pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
            </div>
        </div> 

js代码库:

 var eventschemas = [{ "schema": "Test" }, { "schema": "Another Test" }];

        var AppScope = function () {
            function EventSchemaCondition(data) {
                this.schema = ko.observable(data.schema);


            }

            function Gdetails(data) {
                this.eventschemacondition = ko.observable(data.eventschemacondition);
            }

            function G(data) {
                this.gname = ko.observable(data.gname);
                this.gdetails = ko.observable(data.gdetails);
            }

            function GsViewModel() {
                var self = this;
                self.g = ko.observable(
                new G({
                    gname: "",
                    gdetails: new Gdetails({ eventschemacondition: new EventSchemaCondition({ schema: "" }) })
                }));
            }

            ko.applyBindings(new GsViewModel());
        }();

The full jsfiddle:

真诚感谢任何帮助

谢谢

如果我没理解错的话,你想要的只是下降到 select 'Another test',这是你声明为全局变量的 eventschemas 数组中索引 1 处的项目.

如果您再次打开 jsfiddle 并在 applyBindings 调用之前更改脚本底部的最后一个 schema: ""schema: eventschemas[1] 它将 select 它在下拉列表中.

只需按照以下所述进行一些小改动

视图:(包括optionsValue

<select data-bind="options: eventschemas, optionsText: 'schema',optionsValue:'schema', value:schema, event: {change:setschema}"></select>

ViewModel:

 function EventSchemaCondition(data) { 
                this.schema = ko.observable("Another Test"); //set your default option
                this.setschema = function () {
                  //your code
                };
            }

工作fiddlehere