2012-12-03 93 views
0

我想改變CSS類,當我點擊一個動態添加項目。我確實有doStuffWithThisItem方法中的項目,但是好像這些更改沒有保存到dom樹中。 但我不能得到它的工作。你能發現我做錯了什麼嗎?JQuery addClass不能動態添加項目

 <style type="text/css"> 
     .selectedItem { 
      background-color: red; 
     } 
    </style> 
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js" type="text/javascript"></script> 
    <script type="text/javascript"> 

     jQuery(document).ready(function() { 

      function doStuffWithThisItem(item) { 
       alert(item.id); 
       jQuery(item.id).addClass('selectedItem'); 
      } 

      function parseNodes(nodes, level) { 

       var ol = document.createElement("ul"); 
       for (var i = 0; i < nodes.length; i++) { 
        ol.appendChild(parseChildNode(nodes[i], level)); 
       } 

       return ol; 
      } 

      function parseChildNode(child, level) { 

       var li = document.createElement('li'); 
       jQuery(li).html(child.title) 
        .attr("id", child.id) 
        .click(function() { 

         if (level == 1) { 
          doStuffWithThisItem(this); 
         } 

        }); 

       return li; 
      } 

      window.jsonData = [{ 
        "title": "Item 1", 
        "id": "item1", 
        "description": "Item 1 description" 
       }, 
       { 
        "title": "Item 2", 
        "id": "item2", 
        "description": "item 2 description" 
       }]; 

      jQuery("#someDiv").html(parseNodes(jsonData, 1)); 
     }); 

    </script> 


<div id="someDiv"></div> 

回答

2

請更改:

jQuery(item.id).addClass('selectedItem'); 

要:

jQuery("#"+item.id).addClass('selectedItem'); 

您的選擇有錯

+0

或者將jQuery(項目) –

+0

當然。非常感謝 :-) –

1

你已經在你的doStuffWithThisItem html元素,所以你並不需要去與它的id,你沒有做正確的得到它。

試試這個:

function doStuffWithThisItem(item) { 
    alert(item.id); 
    jQuery(item).addClass('selectedItem'); 
} 
0

你試過用。對和.live處理程序:

jQuery(li).html(child.title) 
       .attr("id", child.id) 
       .on('click',function() { 

        if (level == 1) { 
         doStuffWithThisItem(this); 
        } 

       }); 

jQuery(li).html(child.title) 
       .attr("id", child.id) 
       .live('click',function() { 

        if (level == 1) { 
         doStuffWithThisItem(this); 
        } 

       }); 
0

我認爲這事做的項目被動態添加。我已經在我之前遇到過,並且必須使用.on()方法將事件附加到動態添加的項目。

另外,我覺得你的選擇應該僅僅是項目,而不是item.id

0
jQuery(item.id).addClass('selectedItem'); 

應該是

jQuery('#' + item.id).addClass('selectedItem'); // OR jQuery(item) 

缺少的#ID選擇..

Check Fiddle