如何从knockout.js observableArray中获取所选菜单选项?

我觉得我错过了一些非常基本的东西,但是我无法使用下拉菜单来工作,因为我期望使用Knockout.js.

我有一组要在菜单显示的对象,我需要找到所选的选项并将其发布到服务器.我可以让菜单渲染,但似乎无法获得所选项目的值.我的视图模型如下所示:

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() );

我的视图标记看起来像这样:

<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>

如何让选定的菜单显示在范围内,并发布到服务器? (我假设我在span中渲染的observable与我发布的相同.)我是否需要ProjectFilterItem中的另一个属性,如this.selected = ko.observable(false); ?如果是这样,我将如何将其声明为值的目标?

解决方法

您只需使用 value binding绑定选定的值:

options documentation开始:

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,optionsValue:   'Id',optionsCaption: '-- Select Project --'
    "
></select>

Demo.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...