Skip to content
Categories:

使用 jQuery 製作樹狀目錄

Post date:

過陣子可能有個案子要使用到無限多層的表達方法,參考過 YUI ,但是自己對於 jQuery 比較熟悉,所以就使用 Treeview plugin 來製作。

資料表的結構也很簡單,我規劃下列幾個欄位:

  • 編號 id – int(4) auto_increment)
  • 標籤名稱 label – varchar(50)
  • 父項目編號 parent – int(4)
  • 排序 sort – int(4)

php 端採用遞迴方式實做:

function treeview($parent) {
    $sql = " SELECT * FROM items WHERE parent=$parent";
    $result = mysql_query($sql);
    $output = array();
    
    while($record = mysql_fetch_array($result)){array_push($output, $record);}
    $cc = count($output);
    
    if(!$parent == 0){  
      if($cc > 0) echo ("
    \n"); } for($i=0; $i 0) { $str_a = ""; $str_b = ""; } else { $str_a = ""; $str_b = ""; } echo ("
  • " . $str_a . $output[$i]['label'] . $str_b); treeview($output[$i]['id']); } if(!$parent == 0) { if($cc > 0) echo ("
\n\n"); else echo ("\n"); } }

測試網頁:http://beboss.idv.tw/treeview.php


讀過幾年書,塵世中的迷途大叔。

Comments

  • 您好小弟我是php的新手
    有許多不了解的地方想請教您一下
    請問您資料庫的內容是否可以告知一下以及function.php的原始碼
    再此先向您說聲謝謝了!

  • 我記得 function.php 只是 mysql 的連結:

    <?php
    $link = mysql_pconnect(“hostname”, “username”, “password”) or die(“Could not connect”);
    mysql_select_db(“database”);
    ?>

    以下是資料庫的內容,可以複製後使用 phpMyAdmin 載入下列 sql:

    CREATE TABLE `items` (
    `id` int(11) NOT NULL auto_increment,
    `label` varchar(50) collate utf8_unicode_ci NOT NULL,
    `parent` int(11) NOT NULL,
    `root` int(11) NOT NULL,
    `sort` int(11) NOT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8

    INSERT INTO `items` (`id`, `label`, `parent`, `root`, `sort`) VALUES
    (1, ‘Hardware’, 0, 0, 1),
    (2, ‘Computer’, 0, 0, 2),
    (3, ‘Software’, 0, 0, 3),
    (4, ‘CPU’, 1, 1, 1),
    (5, ‘RAM’, 1, 1, 2),
    (6, ‘MainBoard’, 1, 1, 3),
    (7, ‘Intel’, 4, 1, 1),
    (8, ‘AMD’, 4, 1, 2),
    (9, ‘Core 2 Duo’, 7, 1, 1),
    (10, ‘Core 2 Quad’, 7, 1, 2),
    (11, ‘AM2 Athlon 64’, 8, 1, 1),
    (12, ‘Opteron’, 8, 1, 2),
    (13, ‘Keyboard & Mouse’, 2, 2, 1),
    (14, ‘Printer’, 2, 2, 2),
    (15, ‘Operation System’, 3, 3, 1),
    (16, ‘Image Process’, 3, 3, 2),
    (17, ‘Logitech’, 13, 2, 1),
    (18, ‘Microsoft’, 13, 2, 2);