javascript Knockout.js - 设置一个空的选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15481380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:56:22  来源:igfitidea点击:

knockout.js - setting an empty selection

javascriptknockout.js

提问by rampion

I'm trying to use knockout.js to populate and manage a <select/>box. I'd like the initial value to be empty.

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

However, I'm having trouble trying to force the managed value to be null at any time, let alone initially.

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

For example, consider this fiddle:

例如,考虑这个小提琴

HTML:

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:

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

The select "one"and select "four"buttons work to change the selection by forcing an update of myValue(). However, the clear the selection button doesn't work. The selection is not cleared by myValue(null), which is what I thought was the proper way to do it.

select "one"select "four"按钮的工作通过强制的更新来改变选择myValue()。但是,清除选择按钮不起作用。选择没有被清除myValue(null)这是我认为的正确方法

What am I doing wrong?

我究竟做错了什么?

回答by Joe

You need the optionsCaptionbinding set.

您需要optionsCaption绑定集。

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

Updated Fiddle

更新的小提琴