问题描述
这实际上与我问过的一个问题有关.但这是由于情况略有不同,所以我认为最好是完全创建一个新问题.
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
参数.根据文档:
对对象数组的选择:
<select id="second" data-bind="options: secondDropdownOptions, optionsText: 'title', optionsValue: 'value', value: selectedSecondOptionValue"></select>
正在工作小提琴.
这篇关于在KnockoutJS中使用对象数组时,如何在选择下拉列表中预选择选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!