2013-04-09 131 views
0

我有一個類似於數據樹的json對象。我想交互式地在UI上顯示它。在點擊一個組件時,它的孩子應該被顯示等等。我寫了下面的代碼for循環中動態創建的html元素的Onclick事件

  <!DOCTYPE html> 
      <html> 
      <head> 

      <script src="jquery-1.9.1.js"></script> 
      </head> 
      <body> 
      <div> 
       <ul id="result"></ul> 

      </div> 
      <script> 
      var json_data = { 
       "component": "A", 
       "status": 0, 
       "children": [ 
        { 
         "component": "AA", 
         "status": 0, 
         "children": [ 
          { 
           "component": "AAA", 
           "status": 0, 
           "children": [] 
          }, 
          { 
           "component": "AAB", 
           "status": 2, 
           "children": [] 
          } 
         ] 
        }, 
        { 
         "component": "AB", 
         "status": 0, 
         "children": [ 
          { 
           "component": "ABA", 
           "status": 0, 
           "children": [] 
          }, 
          { 
           "component": "ABB", 
           "status": 1, 
           "children": [] 
          } 
         ] 

        } 
       ] 
      }; 

      $(document).ready($(function(){ 
       var $result = $('#result'); 
       start(json_data) 
       //Root Node display 
       function start(obj) 
       { 

        $('<li id="' + obj.component + '">').text(obj.component + '-'+obj.status).appendTo($result); 
        $("#"+obj.component).click(function(){ 
         displaychildren(obj); 
        }); 

       } 
       Display the children of an element on click by recursion 
       function displaychildren(node) 
       { 
        $.each(node.children,function (i,v){ 
          $('<li id="' + v.component + '">').text(v.component + '-'+v.status).appendTo($result);              
          if$("#"+v.component).click(function(){ 
          alert("Problem is here"); 
          displaychildren(v); 
          }); 

         });      
       } 
       }); 

我面對的問題是displaychildren函數中的onclick函數不起作用。如果onclick條件被刪除,所有組件的所有元素都將顯示出來。我只想顯示所選組件的子項。有誰知道是什麼原因造成的問題

回答

5

有沒有在你的語法錯誤:

if$("#"+v.component).click(function(){ 

應該是(如果你的意思是它是這樣):我猜

if($("#"+v.component).click(function(){ 

您代碼應爲:

$("#"+v.component).click(function(){ 
          alert("Problem is here"); 
          displaychildren(v); 
          } 

由於if()在這裏沒有多大意義,所以在click事件的周圍。

+0

哇只是哇...........它簡單地通過刪除如果.....我認爲這些天來錯誤是在我的對象表示。非常感謝迪克森:) – Praneeth 2013-04-09 11:03:02

+2

沒問題,有時它只需要一個代碼:)一雙新鮮的眼睛 – 2013-04-09 11:04:22

相關問題