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



我试图得到的是dropdownlist中的"另一个测试",而不是默认值"测试"(在加载页面时选择)。

如图所示,在简单的情况下很容易。。但是当你有如下嵌套结构时。。该怎么办.

我的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());
}();

完整的jsfiddle:

衷心感谢您的帮助

感谢

只需要做以下几项小更改

视图:(包括optionsValue)

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

视图模型:

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

工作小提琴此处

如果我理解正确,您只需要让drop选择"另一个测试",它是eventschemas数组中索引1处的项目,您将其声明为全局变量。

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

最新更新