JS
function loadXml() {
$.ajax({
type: 'get',
url: 'test.xml',
dataType: 'xml',
success: function(output) {
$(output).find('name').each(function() {
$('table > tbody').html('<tr><td>'+$(this).text()+'</td></tr>');
});
}
});
}
HTML
<a href="javascript:void(0)" onClick="loadXml()">Click Me</a>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Occupation</th>
<th>Fav Show</th>
</tr>
</thead>
<tbody>
//
</tbody>
</table>
XML
<?xml version="1.0" encoding="UTF-8"?>
<people>
<person>
<name>Sam Uber</name>
<age>22</age>
<occupation>Web Developer</occupation>
<favshow>Batman</favshow>
</person&g开发者_JS百科t;
<person>
<name>Jenna Taylor</name>
<age>18</age>
<occupation>Model</occupation>
<favshow>Family Guy</favshow>
</person>
</people>
The problem is when I click the link it shows the first name "Sam Uber" and that's it. Instead of showing both names from the XML inside the table body. I don't know why this is since that code is within the each() function.
Even stranger is the fact that it works when I alert the names:
alert($(this).text());
instead of
$('table > tbody').html('<tr><td>'+$(this).text()+'</td></tr>');
So I guess the problem is there...
The line $('table > tbody').html('<tr><td>'+$(this).text()+'</td></tr>');
is replacing all of the html inside of tbody
with the content given to the function.
You should append()
the content instead of filling it.
$('table > tbody').append('<tr><td>'+$(this).text()+'</td></tr>');
精彩评论