gpt4 book ai didi

javascript - Knockout JS 任意对象绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 05:41:10 25 4
gpt4 key购买 nike

我对 knockout js 很陌生,我正在尝试自己的例子,所以我有这个

<script>
var Country = function(name, population) {
this.countryName = name;
this.countryPopulation = population;
};

var viewModel = {

availableCountries : ko.observableArray([
new Country("UK", 65000000),
new Country("USA", 320000000),
new Country("Sweden", 29000000)
]),
selectedCountry : ko.observable() // Nothing selected by default
};

$(function(){ko.applyBindings(viewModel)});

</script>

在 View 中

<p>Your country:
<select data-bind="options: availableCountries, optionsText: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"></select>
</p>

<div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
You have chosen a country with population
<span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
</div>

我的问题是我希望下拉菜单在初始化时有一个预选值所以我尝试了这个

selectedCountry : ko.observable(new Country("UK", 65000000))

但它不起作用“选择...”仍然显示为预选选项文本而不是“Uk”,然后我尝试了

selectedCountry : ko.observable(availableCountries[0])

但我一直收到这个错误

“未捕获的类型错误:无法读取未定义的属性‘0’”

我做错了什么,我该如何解决?

最佳答案

在定义 viewModel 对象后,添加以下内容:

viewModel.selectedCountry(viewModel.availableCountries()[0]);

你不能在声明对象时引用它的值(至少我认为你不能),所以你需要在事后进行赋值。

另一种选择是将您的 viewModel 定义为一个函数:

var viewModel = function (){
var self = this;

self.availableCountries = ko.observableArray([
new Country("UK", 65000000),
new Country("USA", 320000000),
new Country("Sweden", 29000000)
]);

self.selectedCountry = ko.observable(self.availableCountries()[0])
};

关于javascript - Knockout JS 任意对象绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20735136/

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