JQuery:无法正确显示表格

问题描述:

最近,我一直在研究一个使用JQuery解析JSON并将其显示在HTML视图中的Web应用程序。我无法弄清楚为什么下面的代码输出表在第一个.append方法之后立即结束标记。JQuery:无法正确显示表格

$("document").ready(function() { 
    $.getJSON("http://localhost:1909/encoders", function(data) { 

     $("#displayencoders").append('<table class="encoders"><tr class="rows"><th class="j">Encoder Name</th><th class="j">Status</th></tr>'); 

     $.each(data, function(i, item) { 
      $("#displayencoders").append("<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>"); 
     }); 

     $("#displayencoders").append("</table>"); 

    }); 
}); 

上述代码将输出下面的HTML。

<table class="encoders"> 
<tbody><tr class="rows"><th class="j">Encoder Name</th><th class="j">Status</th></tr></tbody> 
</table> 
<tr><td>rmcp2-encoder</td><td>inactive</td></tr><tr><td>rmcp2-encvm1</td><td>active</td></tr><tr><td>rmcp2-encvm2</td><td>active</td></tr><tr><td>rmcp2-encvm3</td><td>active</td></tr><tr><td>rmcp2-encvm4</td><td>inactive</td></tr><tr><td>rmcp2-encvm5</td><td>active</td></tr><tr><td>rmcp2-encvm6</td><td>active</td></tr><tr><td>rmcp2-encvm7</td><td>inactive</td></tr><tr><td>rmcp2-encvm8</td><td>inactive</td></tr> 

换句话说,我该怎么修改我现有的jQuery代码到我的标签移动到实际表的末尾?

在此先感谢。

当您使用的append(),在DOM被更新。我认为(每个浏览器可能会有所不同),如果您打开一个元素,将其添加到DOM,浏览器将“帮助”您,并为您关闭标签。 解决它的最好方法,是使函数内的一个变量,只有追加HTML当你把所有的代码:

$("document").ready(function() { 
    $.getJSON("http://localhost:1909/encoders", function(data) { 

     var html = '<table class="encoders"><tr class="rows"><th class="j">Encoder Name</th><th class="j">Status</th></tr>'; 

     $.each(data, function(i, item) { 
      html += "<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>"; 
     }); 
      html += "</table>"; 
     $("#displayencoders").append(html); 

    }); 
}); 
+0

这完美地工作。谢谢你的解释。 – user177215 2010-01-21 17:01:44

我建议修改你的代码:

$("document").ready(function() { 
    $.getJSON("http://localhost:1909/encoders", function(data) { 
     $('<table>').addclass('encoders').appendTo('#displayencoders'); 
     $('<tr class="rows"><th class="j">Encoder Name</th><th class="j">Status</th></tr>').appendTo('.encoders'); 

     $.each(data, function(i, item) { 
      $("<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>").appendTo('.encoders'); 
     }); 

    }); 
}); 

我不认为有必要有表标签是动态创建。开始使用HTML,其中包括:

<table id="encoder-table" class="encoders"> 
    <tr class="rows"> 
     <th class="j">Encoder Name</th> 
     <th class="j">Status</th> 
    </tr> 
</table> 

然后:

$("document").ready(function() { 
    $.getJSON("http://localhost:1909/encoders", function(data) { 

     $.each(data, function(i, item) { 
      $("#encoder-table").append("<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>"); 
     }); 
    }); 
});