gpt4 book ai didi

jquery - selectize 不适用于动态 knockout 选项绑定(bind)

转载 作者:行者123 更新时间:2023-12-01 04:44:20 24 4
gpt4 key购买 nike

我正在使用 knockout.js 和 jquery。 availableBrands 定义为:

self.availableBrands = ko.observableArray();

我的ajax请求方法是:

self.loadBrands = function () {
$.ajax({
url: '/api/Electronic/GetBrands',
dataType: "json",
contentType: "application/json",
cache: false,
type: 'POST',
success: function (data) {
$.each(data,function (i,item) { self.availableBrands.push(item) });
},
error: function (jqXHR, status, thrownError) {
toastr.error("failed to load Brands.Please refresh page and try again", "Error");
}
});
}

我收到的数据是:

enter image description here

更新:我正在使用与 selectize 插件绑定(bind)的 knockout 选项:

<select id="select-category" class="demo-default" data-bind="options: availableBrands,
value: selectedBrand,
optionsCaption: 'Choose brand...'"></select>

js 是:

$('#select-category').selectize({
create: true,
sortField: {
field: 'text',
direction: 'asc'
},
});

现在选择仅显示我硬编码的那些选项。它不显示通过 ajax 加载的选项。

更新2:

loadBrands 函数中我编写self.availableBrands.push('ghi');ghi 显示在选择选项中。但是通过ajax加载的数据并没有显示出来。

我将ajax成功更改为:

success: function (data) {
$.each((data), function (i, item) { console.log(item); });
},

控制台数据如下图

enter image description here

为什么通过ajax加载的数据在select中没有显示出来?

最佳答案

它应该按预期工作,确保您正确引用 jquery

View 模型:

var ViewModel = function (data) {
var self = this;
self.list = ko.observableArray();
$.each(data, function (i,item) {
self.list.push(item)
});
}
ko.applyBindings(new ViewModel([11, 22, 33]));

检查样本here供引用

在本例检查中无需使用 $.each here .

使用 Selectize 插件检查 here 进行更新 .

加载选项后,尝试在ajax成功中应用.selectize

关于jquery - selectize 不适用于动态 knockout 选项绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32345400/

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