2015-04-15 123 views
0

我有一个JSON对象,我试图添加到。下面是我使用(注释掉位似乎也没有做什么,我需要)的代码:将项目添加到JSON对象

$('#classes tbody').on('click', 'tr', function() { 
    $(this).toggleClass('selected');   
    if ($.isEmptyObject(jsonData)) {    
     jsonData = { 
      "row": [ 
      { 
       "OpenClosed": $('tr.selected td:nth-child(1)').text(), 
       "Section": $('tr.selected td:nth-child(2)').text(), 
       "CRN": $('tr.selected td:nth-child(3)').text(), 
       "CreditHours": $('tr.selected td:nth-child(4)').text() 
      } 

      ] 
     }; 
    } 

    else if (!$.isEmptyObject(jsonData)) {       
     jsonData['row'] = { 
       "OpenClosed": $('tr.selected td:nth-child(1)').text(), 
       "Section": $('tr.selected td:nth-child(2)').text(), 
       "CRN": $('tr.selected td:nth-child(3)').text(), 
       "CreditHours": $('tr.selected td:nth-child(4)').text() 
     };    
     //jsonData.row.push = { 
     // "OpenClosed": $('tr.selected td:nth-child(1)').text(), 
     // "Section": $('tr.selected td:nth-child(2)').text(), 
     // "CRN": $('tr.selected td:nth-child(3)').text(), 
     // "CreditHours": $('tr.selected td:nth-child(4)').text() 
     //};       
    }   
}); 

用户点击某行,我需要它来该行地方添加class=selected到JSON对象。目前它似乎追加(在Chrome开发工具中),而不是添加一个新行。当我选择了两行时,我最终得到了这个CRN: "8063780639",其中CRN在单独的行上应该是80637和80639。我需要每次点击添加像行[0],行[1],行[2]等row ...

回答

2

推是不属性,它是一种方法。所以你必须使用(...)

jsonData.row.push({ 
     "OpenClosed": $('tr.selected td:nth-child(1)').text(), 
     "Section": $('tr.selected td:nth-child(2)').text(), 
     "CRN": $('tr.selected td:nth-child(3)').text(), 
     "CreditHours": $('tr.selected td:nth-child(4)').text() 
    }); 
+0

该死的,在我面前:D与我正要写的完全一样。 – MightyLampshade

+0

这是我正确使用push时得到的结果[http://imgur.com/ITAmazn](http://imgur.com/ITAmazn) – Jrow

+0

结果显示我仍然使用'jsonData.row.push =。 ..'而不是'jsonData.row.push(...)' – devnull69