对于下拉列表框的绑定在之前的knockoutjs文章中已经介绍过,今天主要说一下级联的select,事实上,在knockoutjs里,是以数据绑定为中心的,而数据是以面向对象为前提的,而对于级联绑定来说,它也是一种面向对象里关系对象的体现,有了关系对象,我们就可以把级联很容易的开发出来,而不用像之前JS那么麻烦了。
准备数据对象
var Grade_Subject_R = function () {
var self = this;
self.Grades = [
{ 'subjects': [{ 'id': '1', 'name': '语文' },
{ 'id': '2', 'name': '数学' },
{ 'id': '3', 'name': '英语' }],
'arid': '1',
'name': '小学'
},
{ 'subjects': [{ 'id': '1', 'name': '语文' },
{ 'id': '2', 'name': '数学' },
{ 'id': '3', 'name': '英语' },
{ 'id': '4', 'name': '物理' },
{ 'id': '22', 'name': '化学' },
{ 'id': '23', 'name': '生物' }],
'arid': '2',
'name': '初中'
},
{
'subjects': [{ 'id': '1', 'name': '语文' },
{ 'id': '2', 'name': '数学' },
{ 'id': '3', 'name': '英语' },
{ 'id': '4', 'name': '物理' },
{ 'id': '22', 'name': '化学' },
{ 'id': '23', 'name': '生物' },
{ 'id': '24', 'name': '历史' }],
'arid': '3',
'name': '高中'
}
]; self.grade = ko.observable();
self.subject = ko.observable(); /*
当前选中的年级ID为self.grade().id
当前选中的学科ID为self.subject().id HTML代码:
<select data-bind="
options: Grades,
optionsText: 'name',
value:grade,
optionsCaption: '选择年级'">
</select>
<span data-bind="with:grade">
<select data-bind="
visible: $parent.grade,
options: Subjects,
optionsText: 'name',
value:$parent.subject,
optionsCaption: '选择学科'">
</select>
</span> <span data-bind="with:grade">
<!-- ko foreach: Subjects -->
<input type="checkbox" data-bind="value: id, checked: $root.subject" />
<span data-bind="text: name"></span>
<!-- /ko -->
</span> */ }
JS代码
var model = new Grade_Subject_R();
ko.applyBindings(model); for (var i in model.Grades) {
if (model.Grades[i].arid == "") {
model.grade(model.Grades[i]);
break;
}
}
HTML代码
<select data-bind="
options: Grades,
optionsText: 'name',
value:grade,
optionsCaption: '选择年级'">
</select>
<!-- ko with:grade -->
<select data-bind="
visible:$parent.grade,
options: subjects,
optionsText: 'name',
value:$parent.subject,
optionsCaption: '选择学科'">
</select>
<!-- /ko -->
效果截图
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKgAAADUCAIAAACHyf9ZAAAKwklEQVR4nO2dPW7jOBTHVU87V0jPK8wp0rEP5hTbEsgBfAxikSaADzBlBpAvkCZAioGxzZTcgt/koz6cKKb8/j8Y2J1Ykk39+EiKFp8GA1gyXPsLgOsA8UyBeKZAPFMgnikQz5RZ8aMSwyDU2HwzeU/LYRikTt5t7Wi0tFsWR4hvCqVk83PBh6HEazlMkqmNf7C7STWO2btCSpHtrKW1GsRXFUvLYRBS+23ABlwc8c45Tdh+VEKIcIBRiVK8j3nVqmwwvw2k+CVSRyWClaxy2HZ6jC39qIQNe6ko8QRFlwE2YMOIH7UUwyD1hHh/kEJyWqnANhDi57r4pHOejHiTBHs74t1x0nokFcRvzlTEazn4sVk0nDqd6w5M2HJWfPg8qU1eecAmNMW7uE+C26uujTQv+ezwXIpBCDEIpVeKJ6/1wKdAircGkgY3hHfatk8j1JhI1XIYhLDNBSVeSqHG0Mf4j4b47aD7+CAr6dbdZTrV8zYi3nt3b6v0ADoTXw4g4jUevG/ERB+fNPbF30r7tHjXcqf9tZY+nEOX0bp0s58E71uBuXqmQDxTIJ4pEM8UiGcKxDMF4pkC8UyBeKZAPFMgnikQzxSIZwoh/p9bh3l5p8T/uF3Gl1/Myzsjnty6Q8aXX8tf5IngVl7LLYhfuKUt1w2IX7hlq7yWGxG/pPrfkviPlNcC8ezKa1kqflRi1QqHtdtfzBbidbK+S0t3a3B9+194q72wIC5E8Lew+g/ID1evHW2dwK+P+FHJeHfkxPqJ6e/96WwU8XZ9J30feVEnTFEtitXhlfuyCmTHDOetB/HZ8iZqSU26TLrFVtVgy6Y+KWUR8ekpCStD/eKTROLUGYnxUlUFW+WuLj75SlXFzMTn1T753hvGf3oiyNO7Wjx1W/lUU5/v1jwHJVq6tUJ1TdBSKL1A/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