微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐