我是 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/