select - 如何从 knockout.js observableArray 中获取选定的菜单选项?

标签 select drop-down-menu knockout.js

我觉得我错过了一些非常基本的东西,但我无法使用 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)所选值:

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

参见Demo .

关于select - 如何从 knockout.js observableArray 中获取选定的菜单选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13240658/

相关文章:

asp.net - MVC4 - 有没有办法将根路由到 "normal"未处理的 html 页面?

mysql - 选择顶部错误

css - WordPress 主题演示显示子菜单但不显示主题安装

css - Twitter Bootstrap 下拉菜单在折叠的导航栏中创建额外的插入符

javascript - 我可以在 knockout.js 中创建使用其他绑定(bind)的自定义绑定(bind)吗

javascript - knockout : How to conditionally display and store a value dependent on a dropdown?

php - 从列表中选择 <select> 项目并将其交给处理程序 php

c# - 为什么这个 LINQ Select 表达式不起作用

sql-server - 如何选择列和计数(*)?在 SQL 中

jquery - 响应式网站上的 CSS 下拉菜单导致手机出现问题