通过淘汰赛在我的下拉列表中预选一个项目

2024-02-13

我有以下下拉菜单:

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

使用下面的 JavaScript:

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 的元素。

任何想法?

Thanks.

js小提琴:http://jsfiddle.net/RfWVP/276/ http://jsfiddle.net/RfWVP/276/


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

  1. Use the optionsValue绑定并指定'id'作为您想要用作的属性value每个option:

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

    然后设置selectedCategory等于“2”:

    this.selectedCategory = ko.observable(2);
    

    Example: http://jsfiddle.net/RfWVP/281/ http://jsfiddle.net/RfWVP/281/

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

    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);
    

    Example: http://jsfiddle.net/RfWVP/280/ http://jsfiddle.net/RfWVP/280/

您使用哪一个取决于您需要有关所选类别的哪些信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过淘汰赛在我的下拉列表中预选一个项目 的相关文章