3

我想在淘汰赛中获取组合框中所选索引的 ID 是否有可能?

<select id="lstEntreprisesCbx" data-bind="options:Entreprises,
                        optionsText: 'NomEntreprise',
                        optionsCaption: '-- Nouvelle Entreprise --'">
</select>

谢谢

4

1 回答 1

3

您可以使用selectedIndexselect 元素的属性来找出当前选择的选项。

如果你想把它放在一个绑定处理程序中,你可以这样:

ko.bindingHandlers.selectedIndex = {
    init: function(element, valueAccessor) {
        ko.utils.registerEventHandler(element, "change", function() {
             var value = valueAccessor();
            if (ko.isWriteableObservable(value)) {
               value(element.selectedIndex);   
            }
        });
    }
};

这假设您将它绑定到一个可观察对象(如果您想绑定一个不可观察对象,那么它需要更多代码)并且您可以像这样使用它:

<select id="lstEntreprisesCbx" data-bind="options:Entreprises,
                        optionsText: 'NomEntreprise',
                        optionsCaption: '-- Nouvelle Entreprise --',
                        selectedIndex: myIndex">
</select>

这是一个示例:http: //jsfiddle.net/rniemeyer/K6SZQ/

更新

我读过这个问题,因为它特别想要selectedIndex当前选择的值,这可能是错误的。如果您真的想获得类似于id当前选定对象的东西,那么您可以将value绑定与optionsValue选项一起使用。它看起来像:

<select id="lstEntreprisesCbx" data-bind="options:Entreprises,
                        optionsText: 'NomEntreprise',
                        optionsCaption: '-- Nouvelle Entreprise --',
                        value: selectedId,
                        optionsValue: 'id'">
</select>

因此,您指定在绑定中更新哪个值以及在value绑定中使用哪个属性(作为字符串)optionsValue。如果您省略optionsValue,那么它将value用整个对象填充您。如果您的选项数组只是原始值,这也是您将使用的。

示例:http: //jsfiddle.net/rniemeyer/3LyLs/

于 2013-04-21T22:02:28.750 回答