原文链接:http://fenxianglu.cn/noteDeta...

一、拼装li节点

image.png

数据

var list = [ 
  { id: 1, pid: 0, name: '名称1' },
  { id: 2, pid: 1, name: '名称2' },
  { id: 3, pid: 2, name: '名称3' },
  { id: 4, pid: 2, name: '名称4' }
];

递归函数

function recursiveList(list, id) {
    let html = '<ul>';
    list.forEach(function(v) {
      if(v.pid == id) {
         html += '<li><span class="zh-name" data-id="'+ v.id +'">'+ v.name +'</span>'+ recursiveList(list, v.id) +'</ul></li>';
      }
    });
    return html;
}

调用(去除空的<ul></ul>标签,补上结束标签</ul>)

console.log(recursiveList(list, 0).replace(/<ul><\/ul>/g, '') + '</ul>');

结果

<ul>
  <li>
    <span class="zh-name">名称1</span>
    <ul>
      <li>
        <span class="zh-name">名称2</span>
        <ul>
          <li>
            <span class="zh-name">名称3</span></li>
          <li>
            <span class="zh-name">名称4</span></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

二、拼装option节点

image.png

数据

var list = [
  { id: 1, pid: 0, name: "名称1" }
  { id: 2, pid: 1, name: "名称2" }
  { id: 3, pid: 2, name: "名称3" }
  { id: 4, pid: 2, name: "名称4" }
  { id: 5, pid: 1, name: "名称5" }
  { id: 6, pid: 0, name: "名称6" }
];

递归

function recursiveGenerateSectionNode(optionArr, list, id, indent) {
  list.forEach(function(v) {
    if(v.pid == id) {
      optionArr.push('<option value="'+ v.id +'">'+ indent + v.name +'</option>');
      recursiveGenerateSectionNode(optionArr, list, v.id, indent+' ┠ ');
    }
  });
  return optionArr;
}

调用

var optionArr = [];
recursiveGenerateSectionNode(optionArr, list, 0, ' ┠ ');
console.log('<option value="0">顶级</option>' + optionArr.join(''));

结果

<option value="0">顶级</option>
<option value="1"> ┠ 名称1</option>
<option value="2"> ┠  ┠ 名称2</option>
<option value="3"> ┠  ┠  ┠ 名称3</option>
<option value="4"> ┠  ┠  ┠ 名称4</option>
<option value="5"> ┠  ┠ 名称5</option>
<option value="6"> ┠ 名称6</option>

anchovy
1.9k 声望89 粉丝