0
我能夠得到這個工作,除了兩件事情,我只是想不通:級聯下拉框使用Knockout.js
問題1:我需要得到以下兩種但現在只可以實現一個或另一個:
- 選擇選項需要具有價值和文本
- 模型捕獲的selectedOption需要返回所選擇的選項的對象,而不僅僅是選項的值
我可以通過包括或排除從我的選擇標記以下影響這些作品的其中之一:
...data-bind="optionsValue = 'Id'"...
如何能夠做到兩者兼而有之?
問題2:我需要在下拉菜單中設置所選選項,以便從包含用戶首選值的cookie中檢索對象。我下面的實現並沒有成功設置選定的值。我錯過了什麼?
$(document).ready(function(){
var userOption = $.cookie("userPref") == null ? undefined : JSON.parse($.cookie("userPref"));
var model = function(){
this.options = ko.observableArray();
this.childOptions = ko.observableArray();
this.selectedOption = ko.observable(userOption); //this does nothing to set the value
this.selectedOption(userOption); //this also does nothing
this.options.subscribe(function(){
//this.selectedOption() returns an object if optionsValue is excluded from select databinding and returns option value if included
$.cookie("userPref", JSON.stringify(this.selectedOption());
this.childOptions(undefined);
this.childOptions(this.selectedOption() ? this.selectedOption().children : []);
}.bind(this));
};
var viewModel = new model();
ko.applyBindings(viewModel);
$.ajax({
type: "GET",
url: "myurl",
success: function(data){
viewModel.options(data);
}
});
});
<select data-bind="options: options, optionsText: 'text', optionsValue: 'Id', value: selectedOption, optionsCaption: 'Select Option'"></select>
謝謝Chris!我忽略了提及我嘗試使用簡單類型的方法,通過將Id值從存儲對象傳遞給selectedOption作爲字符串和整數。沒有運氣。此外,下拉列表不會回發到任何東西,這就是爲什麼我試圖使用包含所有需要使級聯工作的子對象的對象本身。我不需要/不想爲此功能進行任何訪問數據庫。 – jmease
那麼,表單控件是要發佈的,無論你是否真的打算使用它們,所以無論如何限制簡單類型都是必需的。也許如果你編輯你的問題來解釋你剛剛使用ID時遇到的問題,那麼有人可能會幫助你。 –