Вопрос

I have the following code in index.htm and main.js files of my hybrid application developed using jQuery Mobile and Icenium. I am trying to display JSON data ( array of objects) obtained from an ajax call to a web service in a HTML table. The variable holding this JSON array of objects is called 'msg' in my jQuery code below.

The problem is I am getting skewed html for the table as pasted at end of this question. How can I make sure my output is proper and not skewed?

index.html

 <div id="dataDiv" ><table bgcolor="aliceblue" id="employeesTable"></table></div>

main.js

                //bind the table
                //1.create column headings
                $("<thead><tr>").appendTo('#employeesTable');
                $('<th>#</th>').appendTo('#employeesTable');
                $.each(msg[0], function(key, val) {
                    $('<th>' + key + '</th>').appendTo('#employeesTable');
                });
                 $('<tr></thead><tbody>').appendTo('#employeesTable');
                //2.populate column data into appropriate cells

                $.each(msg, function(index, val) {
                    $('<tr>').appendTo('#employeesTable');
                    $('<td>' + (index + 1) + '</td>').appendTo('#employeesTable');
                    $.each(msg[index], function(key, val) {
                        $('<td id="' + key + '">' + val + '</td>').appendTo('#employeesTable');
                    });
                    $('</tr>').appendTo('#employeesTable');
                });
                  $('</tbody>').appendTo('#employeesTable');

SKEWED OUTPUT from above jQuery

  <table bgcolor="aliceblue" id="employeesTable">
  <thead>
    <tr></tr>
  </thead>
 <th>#</th>
 <th>FirstName</th>
 <th>LastName</th>
 <th>Age</th>
 <th>YearsInJob</th>
 <th>IsManager</th>
 <tbody>
  <tr></tr>
  <tr></tr>
  <tr></tr>
  <tr></tr>
</tbody>
<td>1</td>
<td id="FirstName">Sunil</td>
<td id="LastName">Jha</td>
<td id="Age">28</td>
<td id="YearsInJob">6</td>
<td id="IsManager">true</td>
<td>2</td>
<td id="FirstName">Nikolay</td>
<td id="LastName">Rebello</td>
<td id="Age">35</td>
<td id="YearsInJob">6</td>
<td id="IsManager">true</td>
<td>3</td>
<td id="FirstName">Mike</td>
<td id="LastName">Newton</td>
<td id="Age">32</td>
<td id="YearsInJob">2</td>
<td id="IsManager">false</td>
<td>4</td>
<td id="FirstName">Paul</td>
<td id="LastName">Samath</td>
<td id="Age">24</td>
<td id="YearsInJob">2</td>
<td id="IsManager">false</td>
</table>
Это было полезно?

Решение

You should append to employeesTable only the thead and tbody element, then append to thead and tbody the table rows you need, and finally append to each row the cells.

To do it, just assign to a variable the elements you are creating and you will need to append some element to. Then, append to those variables instead of employeesTable

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top