gpt4 book ai didi

javascript - KnockoutJS 绑定(bind)选择

转载 作者:行者123 更新时间:2023-11-30 17:42:38 24 4
gpt4 key购买 nike

我是 KO 的新手,我遗漏了一些重要的东西:(

请告诉我为什么这些代码不起作用? fiddle 在这里:http://jsfiddle.net/Z8p4B/我很沮丧。为什么 selectedItem 不在“select”中设置值。

HTML:

    <select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedItem"></select>

View 模型:

    var viewModel = {
/*selectedItem: ko.observable(3), I also try but without success */
selectedItem: 3,
items: ko.observableArray()
};

ko.applyBindings(viewModel);

setTimeout(function() {
viewModel.items([
{id: 1, name:"pencil"},
{id: 2, name:"pen"},
{id: 3, name:"marker"},
{id: 4, name:"crayon"}
]);
});

谢谢

最佳答案

您需要设置 selectedItem 之后您填充了 items数组:

var viewModel = {
selectedItem: ko.observable(),
items: ko.observableArray()
};

ko.applyBindings(viewModel);

setTimeout(function() {
viewModel.items([
{id: 1, name:"pencil"},
{id: 2, name:"pen"},
{id: 3, name:"marker"},
{id: 4, name:"crayon"},
]);
viewModel.selectedItem(3);
});

演示 JSFiddle .

在您的原始代码中,KO 正在设置 selectedItemundefined当你调用 ko.applyBindings(viewModel);因为items应用绑定(bind)时集合为空。因此,当您填充 viewModel.items 时你原来的selectedItem丢失(另请参见本 fiddle )。

关于javascript - KnockoutJS 绑定(bind)选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20748656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com