我有一个与 knockout 绑定(bind)的选项,如下所示:
<select id="ddlProducts" data-bind="options: ShowProducts, optionsText: 'pruductskuname', optionsCaption: 'Choose a product...', value: currentproduct"></select>
我有一个 ajax 调用来验证序列号并返回产品名称。我想将所选选项更改为返回产品。我的 ajax 调用返回的是产品名称:pruductskuname
有没有办法根据我的返回设置所选选项?
例如,如果我的 Return == ProductA 的返回,我想在我的选项中找到 ProductA 并将值设置为 ProductA。
这是我的虚拟机:
/* Data View Model */
var myDataViewModel = {
products: ko.observableArray(),
viewserialized: ko.observable(1),
currentordernumer: ko.observable(),
currentserialqty: ko.observable(),
currentproduct: ko.observable(),
dataitems: ko.observableArray()
};
这是我的 ajax 调用,它获取返回消息:
$.ajax({
url: "ServiceURL",
data: { Serial: ko.toJS(myDataViewModel.currentserialqty) },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
/*SET OPTION BINDING HERE BASED ON Result.d */
alert(Result.d);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
最佳答案
有两种方法可以做到这一点,一种是将 optionsValue 设置为 pruductskuname,如下所示:
<select id="ddlProducts" data-bind="options: ShowProducts, optionsText: 'pruductskuname', optionsCaption: 'Choose a product...', value: currentproduct", optionsValue: 'pruductskuname'></select>
这将使 currentproduct 等于产品的名称,因此您在成功回调中所需要做的就是 myDataViewModel.currentproduct(Result.d);
如果你不这样做,你可以
myDataViewModel.currentproduct(ko.utils.arrayFirst(myDataViewModel.products(), function (item)
{
return item.pruductskuname() === Result.d; //note the ()
})
它将搜索具有该名称的项目并将其设置为当前产品。
关于javascript - 使用 Knockout 以编程方式更改选项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19902229/