大家早上好。我正在玩一些 knockout.js,我正在尝试对几个下拉菜单进行级联过滤。假设我有 3 张桌子,
组 -> 子组 -> 部门
And when groups is selected, the subgruoup drop down is filtered and then when the subgroup drop down is selected the sectors is filtered by the subgroup value. 你得到图片。
我已经有了这个代码。
HTML:
<div class="span3">
<label for="grupos">Grupo<i clasS="icon-search"></i></label>
<select class="span12" id="grupos" data-bind="value:grupo">
<option value="1" >A</option>
<option value="2" >B</option>
<option value="3" >C</option>
</select>
</div>
<div class="span3">
<label for="subgrupos">Subgrupo</label>
<!-- ko with: grupo -->
<select class="span12" id="subgrupos" data-bind='options:$parent.subgrupoData, optionsText: "description", optionsCaption: "Select...", optionsValue: "id", value: $parent.subgrupo'> </select>
<!-- /ko -->
</div>
<div class="span3">
<label for="secciones">Seccion</label>
<!-- ko with: subgrupo -->
<select class="span12" id="secciones" data-bind='options:$parent.seccionData, optionsText: "description", optionsCaption: "Select...", optionsValue: "id", value: $parent.seccion'>
</select>
<!-- /ko -->
</div>
和 JS:
var Subgroup = function(_id, _description) { var self = this; self.id = _id; self.description = _description; };
var Section = function(_id, _description) {
var self = this;
self.id = _id;
self.description = _description;
};
var SearchModel = function() {
var self = this;
self.grupo = ko.observable();
self.subgrupo = ko.observable();
self.subgrupoData = ko.observableArray([]);
self.seccion = ko.observable();
self.seccionData = ko.observableArray([]);
self.grupo.subscribe(function() {
$.getJSON("/someurl", {'g':$('#grupos').val()}, function(data) {
var mappedSg = $.map(data, function(item) { return new Subgroup(item.id, item.description) });
self.subgrupoData(mappedSg);
});
self.seccion(undefined);
});
self.subgrupo.subscribe(function() {
if($('#subgrupos')){
$.getJSON("/anotherurl", {'sg':$('#subgrupos').val()}, function(data) {
var mappedSect = $.map(data, function(item) { return new Section(item.id, item.description) });
self.seccionData(mappedSect);
});
}else{
self.seccion(undefined);
}
});
};
ko.applyBindings(new SearchModel());
所以我完成了工作,但我必须编写 if ($('#subgrupos')) 验证,因为如果我更改第一个下拉菜单,第二个也会更改,因此第三个是在没有 id 的情况下进行搜索。
我的问题是,有没有办法避免带有“with”绑定的选择从 DOM 中删除?验证是否有“淘汰”方式来验证?
提前致谢