;(function($) {
$.fn.cascade = function(options) {
var defaults = {
createOptions: function(parentId){
var rets = [];
rets.push('<option value="">-- 请选择 --</option>');
return rets;
}
};
var opts = $.extend(defaults, options);
var $root = $(this);
$root.each(function(k, v){
if($(this).next()!=undefined){
var val = $(this).next().val();
var parentId = null;
if(k>0){
parentId = $($root[k-1]).next().val();
}
if(k==0 || (k>0 && parentId!=null)){
var rets = opts.createOptions(parentId);
var html = "";
if($.type(rets)=="array"){
html = rets.join("");
}else if($.type(rets)=="string"){
html = rets;
}
$(this).html(html);
$(this).val(val);
}
}
});
$root.change(function(){
var currVal = $(this).val();
var index = $root.index(this);
if(index+1<$root.length){
var $next = $($root[index+1]);
$next.empty();//清空下级菜单
if(index==0 || (index>0 && currVal!="")){
var rets = opts.createOptions(currVal);
var html = "";
if($.type(rets)=="array"){
html = rets.join("");
}else if($.type(rets)=="string"){
html = rets;
}
$next.html(html);
$next.val("").trigger("change");
}
}
});
};
})(jQuery);
html
<div class="form-group">
<label for="" class="col-sm-2 control-label">研究领域:</label>
<div class="col-sm-9">
<div class="row">
<input type="hidden" id="professionId" value="${project.profession.id}"/>
<div class="col-sm-4">
<select class="form-control profession"></select>
<c:if test="${!empty project.profession.id}">
<input type="hidden" value="${fn:substring(project.profession.id, 0, 3)}" />
</c:if>
</div>
<div class="col-sm-4">
<select class="form-control profession"></select>
<c:if test="${!empty project.profession.id && project.profession.level>1}">
<input type="hidden" value="${fn:substring(project.profession.id, 0, 6)}" />
</c:if>
</div>
<div class="col-sm-4">
<select class="form-control profession"></select>
<c:if test="${!empty project.profession.id && project.profession.level>2}">
<input type="hidden" value="${fn:substring(project.profession.id, 0, 8)}" />
</c:if>
</div>
</div>
</div>
</div>
说明:select后跟一个隐藏的input存放用来初始化的值
js调用
$("select.profession").cascade({
createOptions: function(parentId){
var rets = [];
rets.push('<option value="">-- 请选择 --</option>');
$.ajax({
type: "POST",
url: "/profession/getProfessions",
data:{
parentId:parentId
},
async:false,
success: function(data){
if(data){
$.each(data,function(i){
rets.push('<option value="'+data[i].id+'">'+data[i].name+'</option>');
});
}
}
});
return rets;
}
});