I am new to jQuery, and js for that matter. I am trying to create a table from XML data, but I can't get the output correct. Here is what I have so far:
HTML:
<table id="daily_fruit">
<tbody>
</tbody>
</table>
jQuery:
var xml = '<daily_fruit><day>Mon</day><type>apple</type><day>Tues</day><type>orange</type><day>Wed</day><type>banana</type><day>Thur</day><type>pear</type></daily_fruit>';
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$($xml).each(function() {
var showTimes = $xml.find('daily_fruit').each(function() {
var $day = $(this).find('day').text();
var $type = $(this).find("type").text();
$("#daily_fruit").find('tbody')
.append($('<tr>')
.append($('<td>')
.append($day))
)
.append($('<td>')
.append($type))
});
});
Current Output:
MonTuesWedThur
appleorangebananapear
Desired Output:
Mon apple
Tues orange
Wed banana
Thur pear
I think I am close, but I just can't figure it out.
Try modifying your XML so that each fruit is within its own tag. Then instead of finding the "daily_fruit" tag for your each loop, use the "fruit" tag.
Here's a jsfiddle: https://jsfiddle.net/57wgab88/
var xml = '<daily_fruit><fruit><day>Mon</day><type>apple</type></fruit><fruit><day>Tues</day><type>orange</type></fruit><fruit><day>Wed</day><type>banana</type></fruit><fruit><day>Thur</day><type>pear</type></fruit></daily_fruit>';
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$($xml).each(function() {
var showTimes = $xml.find('fruit').each(function() {
var $day = $(this).find('day').text();
var $type = $(this).find("type").text();
$("#daily_fruit").find('tbody')
.append($('<tr>')
.append($('<td>')
.append($day))
.append($('<td>')
.append($type))
)
});
});
Given such XML structure, you're supposed to iterate through <day>
elements instead. Assuming that each <day>
is always followed by corresponding <type>
element :
var xml = '<daily_fruit><day>Mon</day><type>apple</type><day>Tues</day><type>orange</type><day>Wed</day><type>banana</type><day>Thur</day><type>pear</type></daily_fruit>'; xmlDoc = $.parseXML(xml), $xml = $(xmlDoc); $($xml).each(function() { var showTimes = $xml.find('day').each(function() { var $day = $(this).text(); var $type = $(this).next("type").text(); $("#daily_fruit").find('tbody') .append($('<tr>') .append($('<td>') .append($day)) .append($('<td>') .append($type)) ) }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="daily_fruit"> <tbody> </tbody> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.