layui tree組件如何異步加載數據,動態添加樹節點


<?php
    
    $data = [
        [ 'id' => 1, 'name' => '江蘇省', 'pid' => 0],
        [ 'id' => 2, 'name' => '徐州市', 'pid' => 1],
        [ 'id' => 3, 'name' => '睢寧縣', 'pid' => 2],
        [ 'id' => 4, 'name' => '雙溝鎮', 'pid' => 3],
        [ 'id' => 5, 'name' => '王集鎮', 'pid' => 3],
        [ 'id' => 6, 'name' => '銅山區', 'pid' => 2],
        [ 'id' => 7, 'name' => '張集鎮', 'pid' => 6],
        [ 'id' => 8, 'name' => '大黃山鎮', 'pid' => 6],
        [ 'id' => 9, 'name' => '南京市', 'pid' => 1],
        [ 'id' => 10, 'name' => '江寧區', 'pid' => 9],
        [ 'id' => 11, 'name' => '鼓樓區', 'pid' => 9],
        [ 'id' => 12, 'name' => '浙江省', 'pid' => 0],
        [ 'id' => 13, 'name' => '杭州市', 'pid' => 12],
        [ 'id' => 14, 'name' => '西湖區', 'pid' => 13]    
    ];

    $res = [];
    $tree = [];
    //整理數組
    foreach ($data as $key => $value) {
        $res[$value['id']] = $value;
        $res[$value['id']]['children'] = [];
    }
    
    unset ($data);
    //查詢子孫
    foreach ($res as $key => $value) {
        if($value['pid'] != 0){
            $res[$value['pid']]['children'][] = &$res[$key];
        }
    }
    //去除雜質
    foreach ($res as $key => $value) {
        if ($value['pid'] == 0){
            $tree[] = $value;
        }
    }
    unset($res);
    
    $tree = json_encode($tree);?>

 

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>樹模塊 - layui</title>
<link rel="stylesheet" href="layui-master/build/css/layui.css">
<style>
body{padding: 50px 100px;}
</style>
</head>
<body>
<?php require 'mytree.php'; ?>

<ul id="demo"></ul>

<script src="layui-master/build/lay/dest/layui.all.js"></script>
<script>

layui.use('tree', function(){
  var tree = layui.tree({
    elem: '#demo' //指定元素
    //,check: 'checkbox' //勾選風格
    ,skin: 'as' //設定皮膚
    ,target: '_blank' //是否新選項卡打開(比如節點返回href才有效)
    ,drag: true
    ,click: function(item){ //點擊節點回調
      console.log(item)
    }
    ,nodes: <?php echo $tree; ?>
  });

});
</script>
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM