我有一个包含大约四列的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>
答案 0 :(得分:1)
为什么不在处理数据时构造表?
<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>
答案 1 :(得分:0)
您应该查看脚本生成的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]);
...