[英]Add table cell using JQuery
我有一個約有四列的HTML表。 我正在使用Ajax查詢數據,而Ajax使用Django從SQL表中提取信息。 對於最后一列,我需要一個下拉菜單。
我從Ajax獲得的JSON信息示例如下:
[[1, "abc", 1, ["[2013-09-30]", "[2013-12-02]"]]
[[2, "def", 1, ["[2013-09-30]"]]
它基本上顯示ID,一些字符串,頻率和日期。 我有25個不同的ID。 每個ID中的前三個數據點都具有相同的信息,但是唯一不同的是我的日期。 這就是為什么我需要一個下拉菜單為每個ID選擇日期的原因。
我的問題是表格中的下拉菜單無法正常工作。 它顯示第一行中的所有日期,而其余行中的所有其他菜單為空白。 我知道循環中存在一個問題,在該循環中我將下拉菜單附加到表中,但是我無法弄清發生了什么。 任何幫助將不勝感激。
HTML
<table id = "templates" border = "1">
<thead>
<tr>
<th> Template ID </th>
<th> Template Name </th>
<th> Freq Multiplier </th>
<th> As of Date </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JQUERY
<script type="text/javascript">
$(document).ready(function fill_table() {
$.ajax({
type:"GET",
url: "/Tplots/ajax_temp/",
dataType:'json',
success: function(response) {
for(var i = 0; i< response.length; i++)
{
var item = response[i];
for (var j = 0; j<10;j++) {
var tempID = item[j];
j = 1;
var tempName = item[j];
j =2;
var freqM = item[j];
j = 3;
var as_of = item[j];
j=4;
$('#templates tbody').append("<tr id = i><td>" + tempID + "</td><td>" + tempName + "</td><td>" + freqM + "</td><td><select name='dropdown' id = 'dropdown'></select></td></tr>");
for (var k = 0; k<as_of.length; k++)
{
var asofdate = as_of[k];
$('#dropdown').append($("<option>"+asofdate+"</option>"));
}
}
}
}
})
})
</script>
為什么在處理數據時不構造表?
<script type="text/javascript">
$(document).ready(function fill_table() {
$.ajax({
type:"GET",
url: "/Tplots/ajax_temp/",
dataType:'json',
success: function(response) {
for(var i = 0; i< response.length; i++)
{
$('#templates tbody').append("<tr>");
var item = response[i];
for (var j = 0; j<4 ;j++) {
if (j <> 3) { // not the last column
$('#templates tbody').append("<td>" + item[j] + "</td>");
} else {
$('#templates tbody').append("<td><select>");
for (var k = 0; k<as_of.length; k++) {
var asofdate = as_of[k];
$('#templates tbody').append("<option>"+asofdate+"</option>");
}
$('#templates tbody').append("</td>");
}
}
$('#templates tbody').append("</tr>");
}
})
})
</script>
您應該看一下腳本生成的HTML。 看起來您正在為所有行和下拉列表分配相同的ID。 分配一個唯一的ID,以便jQuery選擇器可以選擇正確的行或保存您創建的jQuery對象,如下所示:
var $table = $("#templates tbody");
...
var $row = $("<tr>").appendTo($table);
...
var $td = $("<td>").appendTo($row);
var $select = $("<select>").appendTo($td);
for(var k=0,size=as_of.length; k<size; k++)
$("<option>").appendTo($select).text(as_off[k]);
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.