我觉得我错过了一些非常基本的东西,但我无法使用 Knockout.js 使下拉菜单按照我的预期工作。
我有一组想要在菜单中显示的对象,我需要找到选定的选项并将其发布到服务器。我可以渲染菜单,但似乎无法获取所选项目的值。我的 View 模型如下所示:
function ProjectFilterItem( name, id ) {
this.Name = name;
this.Id = id;
}
function FilterViewModel() {
this.projectFilters = ko.observableArray([
new ProjectFilterItem( "foo", "1" ),
new ProjectFilterItem( "bar", "2" ),
new ProjectFilterItem( "baz", "3" )
]);
this.selectedProject = ko.observable();
}
ko.applyBindings( new FilterViewModel() );
我的 View 标记如下所示:
<select
id = "projectMenu"
name = "projectMenu"
data-bind = "
options: projectFilters,
optionsText: 'Name', /* I have to enquote the value or I get a JS error */
optionsValue: 'Id', /* If I put 'selectedProject here, nothing is echoed in the span below */
optionsCaption: '-- Select Project --'
"
></select>
<b>Selected Project:</b> <span data-bind="text: selectedProject"></span>
如何让选定的菜单项显示在范围中,并发布到服务器? (我假设我在跨度中渲染的可观察值与我发布的相同。)我是否需要在 ProjectFilterItem
中使用另一个属性,例如 this.selected = ko.observable(false) ;
?如果是这样,我如何将其声明为值的目标?
最佳答案
您只需要与 value
binding 一起使用绑定(bind)所选值:
Note: For a multi-select list, to set which of the options are selected, or to read which of the options are selected, use the selectedOptions binding. For a single-select list, you can also read and write the selected option using the value binding.
在您的示例中:
<select
id = "projectMenu"
name = "projectMenu"
data-bind = "
value: selectedProject,
options: projectFilters,
optionsText: 'Name',
optionsValue: 'Id',
optionsCaption: '-- Select Project --'
"
></select>
参见Demo .
关于select - 如何从 knockout.js observableArray 中获取选定的菜单选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13240658/