在KnockoutJS中使用对象数组时,如何在选择下拉列表中预选择选项? [英] How to pre-select option in select dropdown when working with array of objects in KnockoutJS?

查看:97
本文介绍了在KnockoutJS中使用对象数组时,如何在选择下拉列表中预选择选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这实际上与我问过的一个问题有关

This is actually related to a question I had asked here. But since, this was in a slightly different context, I thought it was best if I created a new question altogether.

当我使用简单的字符串数组时,我知道如何在下拉列表中预先选择一个选项.

I know how to pre-select an option in the dropdown when I'm working with a simple array of strings.

字符串数组

查看

<select id="first" data-bind="options: firstDropdownOptions, value: selectedFirstOptionValue"></select>

视图模型

firstDropdownOptions: ko.observableArray(['USA','UK','Other']);
selectedFirstOptionValue: ko.observable('UK');

..但是如果它是对象数组,如何预选一个选项?

..but how do I pre-select an option if it's an array of objects?

对象数组

查看

<select id="second" data-bind="options: secondDropdownOptions, optionsText: 'title', value: selectedSecondOptionValue"></select>

查看模型

secondDropdownOptions: ko.observableArray([
    { value: -1, title: 'Select Type' },
    { value: 1, title: 'Option New 1' },
    { value: 2, title: 'Option New 2' }, // I want this option selected initially
    { value: 3, title: 'Option New 3' }
]);
// similarly, how to pre-select the 3rd option in this case?
selectedSecondOptionValue: ko.observable('')

这是小提琴在这里.

我尝试在此处传递整个对象,该值仅作为整数传递.我什至甚至认为,如果我尝试以一种可以显式设置属性的方式呈现<select>下拉列表,那么也许我可以尝试为其操作selected属性.但是我没有得到预期的结果.这是为此的小提琴.

I've tried passing the entire object here, the value only as an integer. I even thought maybe if I try to render the <select> dropdown in a way that I can set the attributes explicitly, then maybe I can try and manipulate the selected attribute for it. But I did not get the expected results. Here is the fiddle for this.

<select data-bind="foreach: secondDropdownOptions">
    <option data-bind="attr: { text: title, value: value}"></option>
</select>

在这种情况下,尽管value属性绑定到下拉列表中的每个<option>,但文本不会绑定.

In this case, the text does not bind, although the value attribute binds to each <option> in the dropdown.

推荐答案

您未指定optionsValue参数.根据文档:

...但是,如果要让用户从以下数组中选择 任意JavaScript对象(不仅是字符串),然后参见 optionsText和optionsValue参数.

...However, if you want to let the user choose from an array of arbitrary JavaScript objects (not merely strings), then see the optionsText and optionsValue parameter.

对对象数组的选择:

<select id="second" data-bind="options: secondDropdownOptions, optionsText: 'title', optionsValue: 'value', value: selectedSecondOptionValue"></select>

正在工作小提琴.

这篇关于在KnockoutJS中使用对象数组时,如何在选择下拉列表中预选择选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆