Knockoutjs 清除组合框中选定的值
我有这个简单的knockout.js应用程序:
视图:
<select data-bind="options: allDocumentTypes , optionsCaption: 'Choose ...', optionsValue: 'id', optionsText: 'name', selectedOptions: selectedDocument"></select>
<span data-bind="click: cl">CLEAR VALUE!</span>
和这个简单的ViewModel:
function documentType(id, name){
this.id = id;
this.name = name;
}
var viewModel = {
allDocumentTypes: ko.observableArray([]),
selectedDocument: ko.observable(''),
cl: function(){
viewModel.selectedDocument('');
}
};
/* load data */
viewModel.allDocumentTypes.push(new documentType(1,'Test 1'));
viewModel.allDocumentTypes.push(new documentType(2,'Test 2'));
ko.applyBindings(viewModel);
我希望在我单击跨度“清除值!”后,在选择中将选择选项“选择...”,但它没有发生。 viewModel 中的值设置为“”(空字符串),这是正确的,但用户仍然在 select 中看到旧值。
有什么办法可以做到这一点吗?
感谢您的帮助:)
I have this simple knockout.js application:
View:
<select data-bind="options: allDocumentTypes , optionsCaption: 'Choose ...', optionsValue: 'id', optionsText: 'name', selectedOptions: selectedDocument"></select>
<span data-bind="click: cl">CLEAR VALUE!</span>
and this simple ViewModel:
function documentType(id, name){
this.id = id;
this.name = name;
}
var viewModel = {
allDocumentTypes: ko.observableArray([]),
selectedDocument: ko.observable(''),
cl: function(){
viewModel.selectedDocument('');
}
};
/* load data */
viewModel.allDocumentTypes.push(new documentType(1,'Test 1'));
viewModel.allDocumentTypes.push(new documentType(2,'Test 2'));
ko.applyBindings(viewModel);
I would expect, that after i click on span "CLEAR VALUE!", in select will be selected option "choose...", but it is not happening.
The value in viewModel is set to "" (empty string), which is right, but user still see old value in select.
Is there any way to do that?
Thanks for helping:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须将绑定类型更改为“value”而不是“selectedOptions”。下一步是在 cl 函数中设置 viewModel.selectedDocument:
You must change binding type to "value" instead of "selectedOptions". Next step is to set viewModel.selectedDocument in cl function:
在某些情况下,将可观察值设置为
null
将不起作用,例如:下面是
HTML
部分:You can't Reset select box by:
Insetead 写下:
In some cases setting the observable value to
null
will not work, for example :And below is the
HTML
part:You can't reset select box by:
Insetead write this:
这是一个html
here is a html