你可以使用select元素的selectedIndex
属性来找出当前选定的选项。
如果你想要把这个绑定处理程序,你可以是这样的:
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
选项。它看起来像:
因此,您所指定的value
更新约束,而在optionsValue
结合使用(字符串)属性,该属性值。如果您省略了optionsValue
,那么它将用整个对象填充您的value
。如果你的选择数组只是原始值,这也是你会用到的。
样品:http://jsfiddle.net/rniemeyer/3LyLs/
非常感谢您的帮助=)。 – Vileps 2013-04-21 22:05:52
为什么不使用'value'绑定?我在这里错过了什么吗? – 2013-04-22 14:44:00
我想我以为他特别想要项目的'selectedIndex'。重新阅读这个问题,也许这不一定是真的。将更新响应。 – 2013-04-22 15:03:00