2011年5月17日 星期二

jstree教學

這一套是free的jquery套件,而且有整合contextmenu。由於官網的教學寫的不太詳細,所以我在這整理一下用法。
官方網站:jstree

//using ajax load tree
("#tree1").jstree({
 "themes": {
  "theme": "default",
  "dots": false,
  "icons": false
  },
 "json_data": {
  "ajax": {
   "url": "../AJAXLOADTREE.do"
  }
 },
 "plugins": ["themes","json_data", "checkbox"]
 }).bind("loaded.jstree", function (event, data) {//tree load完才做其他事情
   refill();
 }).bind("click.jstree", function(event, data) {//checkbox被點擊時事件
  $("#tree").jstree("get_checked").each(function() {
   alert(this.id);//取得nodeId
   alert($("#tree1").jstree("get_text","#"+this.id));//取得node title
   });
 });


function loadTree() {
 $("#tree").jstree({
   "themes": {
    "theme": "default",
    "dots": true,
    "icons": true
   },
   "json_data": {
    "ajax": {
     "url": "../AJAXLOADTREE.do?sessionid="+Math.round(Math.random()*100000)//防止被cache
    }
   },
   "plugins": ["themes", "json_data", "ui", "crrm", "dnd"]
 }).bind('create.jstree', function(e, data) {//新增節點
   // create node
   //alert(data.rslt.name);新增節點名稱
   //var node = data.rslt.obj;新增節點物件
   //alert(data.rslt.parent.attr("id"));父節點Id
   if (data.rslt.parent == -1)//新增根目錄
    setTreeFolder('0', data.rslt.name, '0');
   else
    setTreeFolder('0', data.rslt.name, data.rslt.parent.attr("id"));
 }).bind("move_node.jstree", function(event, data) {//移動節點
   var moved_node = data.rslt.o;
   if (moved_node != null) {
    var parentNode = data.inst._get_parent(moved_node);
    if (parentNode != -1)//有父目錄
     moveTreeFolder($(moved_node).attr('id'), $(parentNode).attr('id'));
    else
     moveTreeFolder($(moved_node).attr('id'), '0'); //移動為根目錄
   }
 });
    
 $("#tree").delegate("a", "click", function(e) {//節點單擊事件
   node = this;
   //TODO
 });

 $("#treeFolder").delegate("a", "dblclick", function(e) {//節點雙擊事件
   node = this;
   //TODO
 });
}

//新增或更新節點
function setTreeFolder(id, folderName, parentFolderId) {
 $.ajax({
  url: '../AJAXSETTREE.do',
  type: "POST",
  data: "Id=" + id + "&FolderName=" + folderName + "&ParentFolderId=" + parentFolderId,
  success: function(data,status){reloadTree();}
 });
}

//移動節點
function moveTreeFolder(id, parentid) {
 $.ajax({
  url: '../AJAXMOVETREE.do',
  type: "POST",
  data: "Id=" + id + "&ParentFolderId=" + parentid,
  success: function(data,status){reloadTree();}
 });
}

//重新載入專卷樹
function reloadTree() {
 $("#treeFolder").empty();
 loadTree();
}

//回填
function refill() {
 var nodeNameArray = $("#nodeNameId").val().split(";");
 for(i=0;i <nodeNameArray.length;i++){
  //用name取id
  var selectedId = $('#tree').find("'a[rel="+nodeNameArray[i]+"]'").parent().attr('id');
  //展開節點
  jQuery.each($('#tree').jstree("get_path", "#" + selectedId, true), function(index, value) {
    $('#tree1').jstree("open_node", "#" + value);
  });
  //回勾
  $('#tree').jstree("check_node", "#" + selectedId);
 }
}