gpt4 book ai didi

javascript - 从 Knockout.js 的下拉列表中获取选定的值

转载 作者:行者123 更新时间:2023-11-30 09:47:34 25 4
gpt4 key购买 nike

我是 Knockout 的新手,在从下拉列表中获取选定值时遇到问题。我尝试将值更改为“selectedCity”,但我得到了 [Object object]。谢谢!

我的 HTML

<select data-bind="options: Cities, optionsText: 'CityNameRu', value: selectCity">
</select>

<span data-bind="text: selectedCity"></span>

knockout

function CityModel(data) {
var self = this;
this.CityId = ko.observable(data.CityId);
this.CityNameRu = ko.observable(data.CityNameRu);
this.CityName = ko.observable(data.CityName);
}

function ViewModel() {
var self = this;
self.Cities = ko.observableArray([]);
self.selectedCity = ko.observable();

self.selectCity = function (city) {
self.selectedCity(city.CityNameRu);
};

self.GetCities = function () {
$.ajax({
type: "GET",
url: '/FetchCities',
dataType: "json",
success: function (data) {
self.SuccessfullyRetrievedModelsFromAjax(data);

},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
};

this.SuccessfullyRetrievedModelsFromAjax = function (models) {
ko.utils.arrayForEach(models, function (model) {
self.Cities.push(new CityModel(model));
});
};

JSON 响应:

[{"CityId":1,"CityName":"philadelphia","CityNameRu":"Филадельфия"},{"CityId":2,"CityName":"new-york","CityNameRu":"Нью Йорк"}

最佳答案

将整个城市对象设置为 selectedCity 的值。您还可以添加一个计算的可观察对象来检索文本。

function ViewModel() {
var self = this;
self.Cities = ko.observableArray([]);
self.selectedCity = ko.observable();

self.selectCity = function (city) {
self.selectedCity(city);
};

self.selectedCityNameRu = ko.pureComputed(function () {
var selectedCity = self.selectedCity();
return selectedCity ? selectedCity.CityNameRu : '';
}, self);

然后在您的 html 中绑定(bind)到 selectedCityNameRu

<span data-bind="text: selectedCityNameRu"></span>

关于javascript - 从 Knockout.js 的下拉列表中获取选定的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38193457/

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