将项添加到JSON对象

时间:2015-04-15 14:52:41

标签: jquery 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在不同的行上。我需要每次点击添加一个row,如行[0],行[1],行[2]等......

1 个答案:

答案 0 :(得分:2)

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

来调用它
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()
    });