我们首先来看下kendoUI官方的下拉框多选:
再来看看telerik RadControls的下拉框多选:
很明显从展现形式上来看,第二种是优于第一种的,至少我是这么认为的 :-)
那我们就对DropDownList 进行扩展吧。在这里顺便提一个知识点,jQuery为开发插件提拱了两个方法:
jQuery.fn.extend(object) 和jQuery.extend(object)
至于他们的区别和使用,可以看看园友的这篇文章,
http://www.cnblogs.com/wyjgreat/archive/2011/07/19/2110754.html
言归正传,继续完成刚刚要做的事情吧 :)
(function ($) { var kendo = window.kendo,
ui = kendo.ui,
DropDownList = ui.DropDownList; var MultiSelectBox = DropDownList.extend({ init: function (element, options) { options.template = kendo.template(
kendo.format('<input type="checkbox" /><span data-value="#= {0} #">#= {1} #</span>',
options.dataValueField,
options.dataTextField
)
); DropDownList.fn.init.call(this, element, options);
}, options: {
name: "MultiSelectBox",
index: -
}, _focus: function (li) {
var that = this
if (that.popup.visible() && li && that.trigger("select", { item: li })) {
that.close();
return;
}
that._select(li);
}, _select: function (li) {
var that = this,
current = that._current,
data = that._data(),
value,
text,
idx; li = that._get(li); if (li && li[]) {
idx = ui.List.inArray(li[], that.ul[]);
if (idx > -) { //获取元素li中checkbox被选中的项
var selecteditems = $(that.ul[]).find("input:checked").closest("li"); value = [];
text = [];
$.each(selecteditems, function (indx, item) {
var obj = $(item).children("span").first();
value.push(obj.attr("data-value"));
text.push(obj.text());
}); that.text(text.join(", "));
that._accessor(value !== undefined ? value : text, idx);
}
} }, value: function (value) {
var that = this,
idx,
valuesList = []; if (value !== undefined) { if (!$.isArray(value)) {
valuesList.push(value);
}
else {
valuesList = value;
} $.each(valuesList, function (indx, item) {
if (item !== null) {
item = item.toString();
} that._valueCalled = true; if (item && that._valueOnFetch(item)) {
return;
} idx = that._index(item); that.select(idx > - ? idx : ); }); }
else {
return that._accessor();
}
} }); ui.plugin(MultiSelectBox); })(jQuery);
而我们在使用的时候就像使用kendoUI其他控件一样
<script type="text/javascript"> $(document).ready(function () {
var data = [
{ Text: "Test1", Value: "" },
{ Text: "Test2", Value: "" },
{ Text: "Test3", Value: "" },
{ Text: "Test4", Value: "" }
]; $("#multiselect").kendoMultiSelectBox({
dataTextField: "Text",
dataValueField: "Value",
dataSource: data
});
}); </script> <input id="multiselect" />
效果如下:
网上也有个解决方案,但它在使用的时候已不像kendoUI控件那样使用了,所以不推荐,倒是可以看看http://jsfiddle.net/bDvkQ/