2010-01-21 82 views
1

最近,我一直在研究一個使用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代碼到我的標籤移動到實際表的末尾?

在此先感謝。

回答

2

當您使用的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

0

我建議修改你的代碼:

$("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'); 
     }); 

    }); 
}); 
0

我不認爲有必要有表標籤是動態創建。開始使用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>"); 
     }); 
    }); 
});