2013-05-20 86 views
4

我有一個jstree對象,用於存儲數據,並且我使用ajax來完成它一步一步的步驟。我調用一個ajax.php文件,該文件將返回HTML格式的節點,具體取決於我發送給它的數據。替換ajax上的jstree節點調用

我的問題如下:我知道我將接收的數據已經包含當前節點的結構,而不是用它從ajax調用接收到的數據替換當前節點,jstree將結構添加到當前節點作爲新的兒子,這不是我想要的。

舉例來說,如果我點擊節點1:

0 
| - 1 
| - 2 

我會得到以下結構:

0 
| - 1 
| | - 1 
| | | - 1.1 
| | | - 1.2 
| - 2 

我不能改變的AJAX調用返回,但是我想這可能是可能的用下面的代碼來干擾一下,用返回的數據替換一個節點,而不是將它作爲當前節點的子節點插入:

$node.jstree({ 
    "plugins" : [ "themes", "html_data" ], 
    "html_data" : { 
     ajax: { 
      url: "ajax.php", 
      data: function(node){ 
       return { 
        index: (node != -1) ? node.attr("id") : 0 
       }; 
      }, 
      type: "POST" 
     } 
    }, 
    animated: 'fast' 
}); 

非常感謝你的回答:)

回答

2

好吧,所以在與jstree插件戰鬥並被勸告改變我的一個朋友的觀點後,我終於決定讓我自己的摺疊/展開樹算法從頭開始,即使對於像我這樣的JavaScript新手來說,使用jQuery和CSS完成工作並不難。 我花了一天,但我吸取了教訓相當不錯...

的jQuery:

$('.closed').on('click', changeContent); 
function changeContent(e) { 
    $('.open').unbind(); 
    $('.closed2').unbind(); 
    $('.closed').unbind(); 
    var $this = $(this); 
    $this.attr('class', 'open'); 
    $.ajax({ 
     type: 'post', 
     url: 'ajax.php', 
     data: { 
      index: $this.attr("id") 
     }, 
     success: function(xhr,msg) { 
      $this.replaceWith(xhr); 
      $('.closed').on('click', changeContent); 
      UpdateOpen(); 
     } 
    }); 
} 

function UpdateOpen(e) { 
    $('.open').unbind(); 
    $('.closed2').unbind(); 
    $('.open, .closed2').on('click', function(e) { 
     e.stopPropagation(); 
     $('.open').unbind(); 
     $('.closed2').unbind(); 
     var $this = $(e.currentTarget); 
     if($this.attr('class') == 'closed2') { 
      $this.attr('class', 'open'); 
      $this.children('ul').show(); 
      UpdateOpen(e); 
     } else if($this.attr('class') == 'open') { 
      $this.attr('class', 'closed2'); 
      $this.children('ul').hide(); 
      UpdateOpen(e); 
     } 
    }); 
} 

CSS:

.closed {padding-left: 7px; list-style-type: none; background: URL("/img/plus.gif") left top no-repeat; } 
.closed2 {padding-left: 7px; list-style-type: none; border-left: 1px dotted; background: URL("/img/plus.gif") left top no-repeat; } 
.open {padding-left: 7px; list-style-type: none; border-left: 1px dotted; background: URL("/img/minus.gif") left top no-repeat; } 

我知道這是不是最好的實現,但是這就是我我來了解JavaScript的知識。請注意,這段代碼取決於ajax.php返回數據的方式。

+0

始終將代碼發佈回答! ; ^) – ruffin