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

前端之家收集整理的这篇文章主要介绍了如何从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.

原文链接:https://www.f2er.com/js/159673.html

猜你在找的JavaScript相关文章