本文介绍了在下拉菜单中预先选择我的下拉菜单中的一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下下拉菜单:

<div>
    Dummy
    <select data-bind="options: categories, optionsText: 'description', value: 2"></select>
</div>

使用以下javascript:

With the javascript below:

function ViewModel()
{

    this.categories = ko.observableArray([
            new Category(1, "Non classé"),
            new Category(2, "Non nucléaire"),
            new Category(3, "Classe II irradié"),
            new Category(4, "Classe III")
    ]);

    // Constructor for an object with two properties
    function Category(id, description) {
        this.id = id;
        this.description = description;
    };
}

ko.applyBindings(new ViewModel());

我想在下拉列表中预先选择ID为2的元素.

I would like to pre-select the element with the id of 2 in the dropdown.

有什么主意吗?

谢谢.

jsFiddle: http://jsfiddle.net/RfWVP/276/

jsFiddle: http://jsfiddle.net/RfWVP/276/

推荐答案

我可以想到两种方法来做到这一点.无论哪种方式,您都必须添加一个selectedCategory可观察属性以存储跟踪当前选定的选项.

Two ways I can think of to do this. Either way you'll have to add a selectedCategory observable property to store track the currently selected option.

  1. 使用optionsValue绑定并指定'id'作为要用作每个optionvalue的属性:

  1. Use the optionsValue binding and specify 'id' as the property you'd like to use as the value of each option:

<select data-bind="options: categories,
                   optionsText: 'description',
                   value: selectedCategory,
                   optionsValue: 'id'">
</select>

然后将selectedCategory设置为等于"2":

Then set selectedCategory equal to "2":

this.selectedCategory = ko.observable(2);

示例: http://jsfiddle.net/RfWVP/281/

在创建可观察的类别数组之前创建ID为"2"的类别,并将selectedCategory设置为等于该类别:

Create the category with id "2" before creating your observable array of categories and set the selectedCategory equal to that category:

var selected = new Category(2, "Non nucléaire");

this.categories = ko.observableArray([
    new Category(1, "Non classé"),
    selected,
    new Category(3, "Classe II irradié"),
    new Category(4, "Classe III")
]);

this.selectedCategory = ko.observable(selected);

示例: http://jsfiddle.net/RfWVP/280/

使用哪种类型取决于您需要有关所选类别的哪些信息.

Which one you use depends on what information you need about the selected category.

这篇关于在下拉菜单中预先选择我的下拉菜单中的一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 09:46