【问题标题】:knockoutjs 'optionsValue' doesn't work淘汰赛'optionsValue'不起作用
【发布时间】:2012-10-19 07:41:35
【问题描述】:

我的代码不起作用。 这里是http://jsfiddle.net/JPBarbosa/uxwTM/4/。

数据绑定参数optionsValue不像参数optionsText。

我对两者都使用相同的功能!

<select data-bind="options: times, optionsText: function(item) { return item.toLocaleTimeString(); }, optionsValue: function(item) { return item.toLocaleTimeString(); }, value: selectedTime"></select>

问候,JP。

【问题讨论】:

标签: knockout.js


【解决方案1】:

您为optionsValue 传递的对象必须是与要用作值的属性名称相对应的字符串。您不能将其设置为这样的值,不幸的是,它与 optionsText 的工作方式不同。

将times 数组映射到您想要的值会更容易。

<select data-bind="options: ko.utils.arrayMap(times(), function (time) { return time.toLocaleTimeString(); }), value: selectedTime"></select>

尽管您希望将映射代码保持在您的视野之外。所以添加一个计算的 observable 到你的视图模型中,返回映射的值。

var ViewModel = function() {
    // ...
    self.mappedTimes = ko.computed(function () {
        return ko.utils.arrayMap(self.times(), function (time) {
            return time.toLocaleTimeString();
        });
    })
};
<select data-bind="options: mappedTimes, value: selectedTime"></select>

Updated fiddle

【讨论】:

    猜你喜欢
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 2014-06-19
    • 2016-02-17
    • 2016-08-21
    • 1970-01-01
    相关资源
    最近更新 更多