-
Notifications
You must be signed in to change notification settings - Fork 1
/
lcCascade.html
116 lines (103 loc) · 3.4 KB
/
lcCascade.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div.cascader{
position: relative;
/*background: red*/
}
input{
display: block;
}
ul{
float: left;
width: 200px;
border: 1px solid #ccc;
margin-top: 0px;
/*display: none;*/
}
li{
width: 200px;
overflow: hidden;
text-align: left;
}
.selected{
background: #f0f0f0;
}
</style>
</head>
<body>
<div class="cascader">
</div>
<script type="text/javascript" src="location.js"></script>
<script>
var llocation = llocation;
new LcCascader('div.cascader',llocation);
function LcCascader(div,data) {
this.data = data;
//要注意把nodelist换成节点
this.div = document.querySelectorAll(div)[0];
this.ulList = this.div.getElementsByTagName('ul');
this.locationList = [];
var _this = this;
var lastUl0Index = 0;
var lastUl1Index = 0;
var input = document.createElement('input');
this.div.appendChild(input);
input.addEventListener('click', function () {
_this.clickUl(0, data);
})
console.log(input);
//重新实现,现在省级的地址也通过传入data再生成,之前先生成了省级的地址,导致想递归实现时,不知道怎样构造参数,下次被问题困住时,可以重新构思业务逻辑的执行顺序。
this.clickUl = function(ulIndex,data){
var _this = this;
var ul;
if(!data||data.length === 0){
this.div.getElementsByTagName('input')[0].value = this.locationList.join('');
for(let i = 0; i < ulIndex; i++){
this.div.removeChild(this.div.lastChild);
}
return;
}
while(this.ulList.length > ulIndex){
this.div.removeChild(this.ulList[this.ulList.length -1])
}
if(!this.ulList[ulIndex]){
ul = document.createElement('ul');
this.div.appendChild(ul);
}
ul.addEventListener('click',function(e){
var tar = e.target;
if(tar.tagName == 'LI'){
var item = data[tar.index];
_this.setSelectAttr(tar.index,ulIndex);
_this.locationList.splice(ulIndex + 1, _this.locationList.length);
_this.locationList[ulIndex] = item.name;
_this.clickUl(ulIndex + 1, item.children);
}
})
data.forEach((item, index) => {
var li = document.createElement('li');
li.index = index;
li.innerText = item.name;
ul.appendChild(li);
})
}
this.setSelectAttr = function(tarIndex,ulIndex){
if(ulIndex == 0){
this.ulList[0].children[lastUl0Index].removeAttribute('class');
this.ulList[0].children[tarIndex].setAttribute('class','selected');
lastUl0Index = tarIndex;
lastUl1Index = 0;
}else if(ulIndex == 1){
this.ulList[1].children[lastUl1Index].removeAttribute('class');
this.ulList[1].children[tarIndex].setAttribute('class','selected');
lastUl1Index = tarIndex;
}
}
}
</script>
</body>
</html>