2014-05-06 28 views
2

我想添加新的數據(從JSON)到現有的表(使用jQuery)。從JSON添加新的數據到現有的表

在我的HTML我有這個表,例如:

<table data-role="table" data-mode="columntoggle" class="ui-responsive" data-column-btn-text="Filter Columns" id="MyTable"> 
    <thead> 
    <tr> 
     <th data-priority="1">A</th> 
     <th data-priority="2">B</th> 
     <th data-priority="3">C</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
     <td>a1</td> 
     <td>b1</td> 
     <td>c1</td> 
    </tr> 
    </tbody> 
    </table> 

我試圖做到這一點(從JSON添加新的數據):

var response = [{ 
     "A":"a2", 
     "B":"b2", 
     "C":"c2" 
    }, 
    { 
     "A":"a3", 
     "B":"b3", 
     "C":"c3" 
    }, 
    { 
     "A":"a4", 
     "B":"b4", 
     "C":"c4" 
    }]; 

    $.each(response, function(i, item) { 
       $('<tr>').html(
       //"<tr>" + 
       "<td>" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td>" + "</tr>").appendTo('#MyTable'); 
     }); 

爲什麼它不工作?

+0

你是否同意,如果追加到'#MyTable',新的元素將超出'tbody'或'thead'元素? – DontVoteMeDown

+0

是的,我同意你的意見。我不知道如何改變/修復它。 – yoka

+0

我希望我能幫上忙。謝謝。 – DontVoteMeDown

回答

1

您將內容附加到表格本身,而不是附加到theadtbody元素,這是應該完成的操作。嘗試改變你的選擇.appendTo#MyTable tbody,它會工作。 Demo here.

+0

謝謝。這很有幫助。 – yoka

0

您正在以錯誤的方式訪問對象。請嘗試此代碼段。

$.each(response, function(i, item) { 
        $('<tr>').html(
         "<td>" + item.A + "</td><td>" + item.B + "</td><td>" + item.C + "</td>" + "</tr>").appendTo('#MyTable tbody'); 
      }); 
0

使用$( '<TBODY> ').append而不是$(' <TR>')。html的()。

$.each(response, function(i, item) { 
    $('<tbody>').append(
    "<td>" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td>" + "</tr>").appendTo('#MyTable'); 
}); 

你可以在this JSFiddle看到它的行動。

+0

爲什麼不使用'item.A'而不是'response [i] .A'這樣的對象?如果你在DOM中有兩個'tbody'怎麼辦? –

+0

沒有特別的理由不這樣做,我只是用最小的改變複製了問題中的代碼,以幫助他看出差異。你的回答方式一樣好。 – TML

+1

我相信最好向OP展示最佳實踐。雖然這只是我個人的意見:) –

0

請嘗試下面的代碼片段。這會在html中創建'tr'元素。

$.each(response, function(i, item) { 
$("#MyTable tbody").append("<tr> <td>" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td> </tr>");     
      }); 
+0

爲什麼不像'item.A'而不是'response [i] .A'那樣訪問對象? –

+0

它沒有區別。我只是在那裏,因爲這就是問題所在。 –

+0

國際海事組織,這是很好的表現出一些可惜的處理器:頁 –

0

這樣做:

table_html = ''; 
$.each(response, function(index, value) { 
table_html += "<tr><td>"+value["A"]+"</td><td>"+value["B"]+"</td><td>"+value["C"]+"</td></tr>" 
     }); 

給予一定的ID來<tbody>標籤。

$("tbodyid").html(table_html); 
相關問題