DIV CSS 佈局教程網

jQuery + zTree 動態非同步樹的實作
編輯:JQuery特效代碼     

用 zTree 搭配 Ajax 做非同步載入的樹狀結構,設定寫成一個物件即可,程式相當乾淨。

// 業務類型樹設定
var settingOther = {
  edit: { enable: false },
  // 非同步載入
  async: {
    enable: true,
    url: "initCoagencyTree.action",
    autoParam: ["id", "name=n"],
    otherParam: { "otherParam": "zTreeAsyncTest" },
    dataFilter: filter
  },
  // 簡易資料格式
  data: { simpleData: { enable: true } },
  // 回呼函式
  callback: { beforeClick: beforeClick, onClick: onClick }
};

// 點擊前:把節點資訊寫進表單
function beforeClick(treeId, treeNode, clickFlag) {
  if (clickFlag == 1) {
    $("#coagencyId").attr("value", treeNode.id);
    $("#parentId").attr("value", treeNode.pId);
    parent.document.getElementById("name").value = treeNode.name;
  } else {
    $("#coagencyId").attr("value", null);   // 取消選中則清空
    $("#parentId").attr("value", null);
  }
  return (treeNode.click != false);
}

function onClick(event, treeId, treeNode, clickFlag) {
  parent.showCoagencyDetail();
}

// 非同步資料的轉換函式
function filter(treeId, parentNode, childNodes) {
  if (!childNodes) return null;
  for (var i = 0; i < childNodes.length; i++) {
    childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
  }
  return childNodes;
}

// 初始化
$(document).ready(function () {
  $.fn.zTree.init($("#coagencyTree"), settingOther);
});

頁面只需一個容器:

<ul id="coagencyTree" class="ztree" style="height: 640px"></ul>

幾個關鍵設定值得說明:simpleData.enable 讓後端可以用 id / pId 的扁平結構回傳,不必組巢狀 JSON;autoParam 決定點擊展開時帶哪些參數去請求子節點;dataFilter 則是資料落地前的加工點,這裡用來把被跳脫的點符號還原。

實務提醒:autoParam 中的 "name=n" 表示把節點的 name 更名為 n 再送出,後端要對應處理;另外 .attr("value", ...) 設定 hidden 欄位建議改用 .val(),語意更準確。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved