var selIndex = 0;
var arr = [];
//(1)每次点击select时候,selIndex都加1,且push到数组arr
//(2) 循环数组arr,需要将当前点击select【cureentIndex】之后所有的select移除,移除之后在继续重新请求,添加下级
function getGroupList(fatherId, selIndexStr) {
if (selIndexStr && fatherId != 0) {
/*【1】在第一次已经生成select的基础之上,点击继续生成新的select
【2】每点击一次数组arr就增加一项自增的数字,代表所有生成的select的索引
【3】每次切换select选项值,需要将后面所有的select移除,以及将arr中代表的后面select的索引也删除,
重新请求加载下级区划列表,新生成的区划列表未被点击的时候是没有被记录在arr索引中,
只有点击change事件才可以添加索引项到arr中,以备处理
*/
//点击select生成下级区划
selIndex++;
arr.push(selIndex);
// console.log(arr)
var cureentIndex = selIndexStr.substr(3);
var deleteKey = '';
for (var key in arr) {
if (arr[key] > cureentIndex) {
$("#sel" + arr[key]).remove();
}
if (arr[key] == cureentIndex) {
deleteKey = eval(key) + 1;
}
}
arr.splice(deleteKey);
selIndex = cureentIndex;
if(fatherId.length==12){ //明确已到最后一级,将不再加载下一级
return false;
}
ajaxRequest(fatherId, selIndex);
} else if (selIndexStr == '' && fatherId != 0) {
//第一次请求生成下级区划
ajaxRequest(fatherId, selIndex);
}else if(fatherId == 0){ //选择“请选择”的时候,需要将后面的select全部清空
selIndex++;
arr.push(selIndex);
var cureentIndex = selIndexStr.substr(3);
var deleteKey = '';
for (var key in arr) {
if (arr[key] > cureentIndex) {
$("#sel" + arr[key]).remove();
}
if (arr[key] == cureentIndex) {
deleteKey = eval(key) + 1;
}
}
arr.splice(deleteKey);
selIndex = cureentIndex;
}
}
//页面加载完成,第一次请求下级数据,并创建第一个select
window.onload = function () {
var mygroup = document.getElementById('mygroup').value;
getGroupList(mygroup, '');
}
//ajax 请求下级数据
function ajaxRequest(fatherId, selIndex) {
$.ajax({
type: 'get',
url: '../administrator/group.php?action=grouplist',
async: true,
data: { "fatherId": fatherId },
success: function (json) {
var json = JSON.parse(json);
if (json.state == 1) {
var select = '<select onchange="getGroupList(this.value,this.id)" name="group[]" id="sel' + (eval(selIndex) + 1) + '" class="groupArea"><option value="0">请选择</option></select>';
$("#selectBox").append(select);
var optionList = '';
for (var i = 0; i < json.count; i++) {
optionList += '<option value="' + json.list[i].group_id + '">' + json.list[i].group_name + '</option>';
}
$("#sel" + (eval(selIndex) + 1)).append(optionList);
} else {
}
}
})
}