求大神指点js生成树结构

JavaScript025

求大神指点js生成树结构,第1张

// 生成树结构

function tree(list) {

const result = []

for (let value of list) {

// 排除空字符串的情况

if (!value) {

continue

}

const values = value.split('/')

// 查找树结构的当前级别是否已经存在,不存在则创建对象,并添加入列表。

let current = result.find(item =>item.name === values[0])

if (current === void 0) {

current = {}

result.push(current)

}

for (let i = 0, length = values.lengthi <lengthi++) {

current.name = values[i]

if (i <length - 1) {

// 如果还有下一级内容,判断当前是否有 children,没有则构建.

if (current.children === void 0) {

current.children = []

}

// 查找下一级对象,为下一遍遍历构建对象

let nextCurrent = current.children.find(item =>item.name === values[i + 1])

if (nextCurrent === void 0) {

nextCurrent = {}

current.children.push(nextCurrent)

}

current = nextCurrent

}

}

}

return result

}

============ 假装分割线 ===========

以上代码是生成树的函数,调用 tree 函数并传入你的 input 数据,返回值就是生成的树。百科没找到传代码的地方了。

我之前写过一个,很简单,也就下面几个函数:

function topOfList()

{

var btn = document.getElementById('topOfListBtn')

if(btn.state == 'spaned')

{

var forms = document.getElementsByTagName('form')

var timeSpan = 50

for(var i = 0i<forms.lengthi++)

{

var form = forms[i]

if(form.id.indexOf('Top') >-1)

{

ShinkSlowly(form,timeSpan)

timeSpan += 50

}

}

btn.state = 'unspaned'

changeBtnImg('topOfListImg','img/unspaned.jpg')

tellConsoleSpanSate()

}

else

{

var forms = document.getElementsByTagName('form')

var timeSpan = 50

for(var i = 0i<forms.lengthi++)

{

var form = forms[i]

if(form.id.indexOf('Top') >-1)

{

SpanSlowly(form,timeSpan)

timeSpan += 50

}

}

btn.state = 'spaned'

changeBtnImg('topOfListImg','img/spaned.jpg')

tellConsoleSpanSate()

}

}

function bottomOfList()

{

var btn = document.getElementById('bottomOfListBtn')

if(btn.state == 'spaned')

{

var forms = document.getElementsByTagName('form')

var timeSpan = 50

for(var i = 0i<forms.lengthi++)

{

var form = forms[i]

if(form.id.indexOf('Bottom') >-1)

{

ShinkSlowly(form,timeSpan)

timeSpan += 50

}

}

btn.state = 'unspaned'

changeBtnImg('bottomOfListImg','img/unspaned.jpg')

tellConsoleSpanSate()

}

else

{

var forms = document.getElementsByTagName('form')

var timeSpan = 50

for(var i = 0i<forms.lengthi++)

{

var form = forms[i]

if(form.id.indexOf('Bottom') >-1)

{

SpanSlowly(form,timeSpan)

timeSpan += 50

}

}

btn.state = 'spaned'

changeBtnImg('bottomOfListImg','img/spaned.jpg')

tellConsoleSpanSate()

}

}

function ShinkSlowly(form,timeSpan)//控制按钮收缩的函数

{

setTimeout(function()

{

form.style.display = 'none'

}

,timeSpan)

}

function SpanSlowly(form,timeSpan)//控制按钮展开的函数

{

setTimeout(function()

{

form.style.display = ''//alert(form.id)

}

,timeSpan)

}

function changeBtnImg(imgId, imgSrc)

{

document.getElementById(imgId).src=imgSrc//'img/unspaned.jpg''img/spaned.jpg'

}

其中,imgSrc要换成你硬盘里存在的图片路径。然后在你的+号图片的单击事件响应使用topOfList()函数即可,我测试过,可用。ShinkSlowly()函数内部可以控制张开和收缩的速度。