/**
* @念凝笙
* 三级联动 const Three new NNS_Select(DOM, 3, [...])
* 然后 Three.create()...
*/
class NNS_Select {
/**
* @params:
* container: 容纳级联的容器
* num: 级联数目
* data: 数据
* 数据格式JSON对象如: [{name: '四川',children: [{name: '成都',
* children:[...]}...]}...]
*/
constructor(container, num, data) {
this.container = container
this.num = num
this.data = data
}
create() {
let selectors = []
let count = 0
let data = this.data
let num = this.num
selectors = this.createSelectors(num)
while(count < num) {
this.container.appendChild(selectors[count++])
}
this.addToSelect(data, selectors, 0, num)
this.addChangeEvent(selectors, num, data)
}
createSelectors(num) {
let count = 0
let selectors = []
while(count < num) {
let selector = document.createElement('select')
selector.dataset['id'] = 0
selector.innerHTML = `<option value=0>没有下级选项</option>`
selectors[count++] = selector
}
return selectors
}
createOptions(data) {
let html = ''
let count = 0
let len = data.length
while(count < len) {
html += `<option value=${count}>${data[count].name}</option>`
count++
}
return html
}
addToSelect(data, selectors, count, num) {
if(count === num || !data) {
if(count < num) {
selectors[count].innerHTML = `<option value=0>没有下级选项</option>`
}
return
}
selectors[count].innerHTML = this.createOptions(data)
return this.addToSelect(data[0].childern, selectors, count + 1, num)
}
findChild(data, start, currIndex, selectors) {
let find = (d, i) => {
if(i > currIndex) {
return d
}
let pos = selectors[i].dataset['id']
return find(d[pos].childern, i + 1)
}
return find(data, start)
}
hasChild(data, start, num, selectors) {
if(!data) {
console.log(true)
while(start < num) {
console.log(start)
selectors[start++].innerHTML = `<option value=0>没有下级选项</option>`
}
return false
}
return true
}
handleChange(me, selectors, curr, data) {
let _this = selectors[curr]
_this.dataset['id'] = _this.options[_this.selectedIndex].value
let firstPos = selectors[0].dataset['id']
let _data = []
let slen = selectors.length
_data = me.findChild(data, 0, curr, selectors)
if(!me.hasChild(_data, curr + 1, slen, selectors)) {
return true
}
selectors[curr + 1].innerHTML = me.createOptions(_data)
me.addToSelect(_data, selectors, curr + 1, slen)
}
addChangeEvent(selectors, count, data) {
selectors[--count].onchange = function() {
console.log(true)
return true
}
while(--count >= 0) {
selectors[count].onchange = this.handleChange.bind(null, this, selectors, count, data)
}
}
}
复制代码
转载于:https://juejin.im/post/5a740d11f265da4e7c1857a8