[英]Generating a table with jQuery with XML data
I am new to jQuery, and js for that matter. 我是jQuery和js的新手。 I am trying to create a table from XML data, but I can't get the output correct. 我正在尝试从XML数据创建表,但是我无法正确获得输出。 Here is what I have so far: 这是我到目前为止的内容:
HTML: HTML:
<table id="daily_fruit">
<tbody>
</tbody>
</table>
jQuery: 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. 尝试修改XML,以使每个水果都在其自己的标签内。 Then instead of finding the "daily_fruit" tag for your each loop, use the "fruit" tag. 然后,不要为每个循环找到“ daily_fruit”标签,而应使用“ fruit”标签。
Here's a jsfiddle: https://jsfiddle.net/57wgab88/ 这是一个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. 给定这样的XML结构,您应该改为遍历<day>
元素。 Assuming that each <day>
is always followed by corresponding <type>
element : 假设每个<day>
后面总是跟着相应的<type>
元素:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.