2013-04-09 135 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

相关问题