knockout.js - 设置一个空的选择

时间:2013-03-18 16:05:05

标签: javascript knockout.js

我正在尝试使用knockout.js来填充和管理<select/>框。我希望初始值为空。

但是,我无法在任何时候尝试强制托管值为空,更不用说最初了。

例如,考虑this fiddle

HTML:

<select data-bind="options: myOptions, value: myValue"></select> aka
<span data-bind="text: myValue"></span>

<div>
    <button data-bind="click: setMyValue(null)">clear the selection</button>
    <button data-bind="click: setMyValue('one')">select "one"</button>
    <button data-bind="click: setMyValue('four')">select "four"</button>
</div>
<ul data-bind="foreach: log">
    <li>message: <span data-bind="text: message"></span></li>
</ul>

JS:

function Model() {
    var self = this;
    self.myOptions = ['one', 'two', 'three', 'four'];
    self.myValue = ko.observable();
    self.setMyValue = function (val) {
        return function(){
            this.log.push({
                message: "ok, trying to set value as " + val
            });
            self.myValue(val);
        };
    };
    self.log = ko.observableArray([]);
}
var model = new Model();
ko.applyBindings(model);

select "one"select "four"按钮用于通过强制更新myValue()来更改选择。但是,清除选择按钮不起作用。 myValue(null)which is what I thought was the proper way to do it未清除选择。

我做错了什么?

1 个答案:

答案 0 :(得分:32)

您需要optionsCaption绑定集。

<select data-bind="options: myOptions, value: myValue, optionsCaption: 'select...'"></select>

Updated Fiddle