【发布时间】:2014-02-10 14:56:28
【问题描述】:
我正在使用 jQuery 来解析和输出 XML。我有一个嵌套循环来输出 TASKS 的所有子代,但每次迭代都会立即输出所有子代,而不是每行一个。
<xml version="1.0">
<choices>
<choice id="1" name="Type 1">
<description>
Example a
</description>
<tasks>
<task>Do this</task>
<task>Do that</task>
</tasks>
</choice>
<choice id="2" name="Type 2">
<description>
Example b
</description>
<tasks>
<task>Do other</task>
<task>Do something</task>
</tasks>
</choice>
</choices>
我的脚本:
$(function(){
"use strict";
//Above XML content is being passed as a string for this example
var str = "<xml version='1.0'><choices><choice id=\"1\" name=\"Type 1\"><description>Example a</description><tasks><task>Do this</task><task>Do that</task></tasks></choice><choice id=\"2\" name=\"Type 2\"><description>Example b</description><tasks><task>Do other</task><task>Do something</task></tasks></choice></choices></xml>";
var xmlDoc = $.parseXML(str);
var $xml = $(xmlDoc);
var temp = {};
$xml.find('choice').each(function() {
var $this = $(this);
temp.id = $this.attr('id');
temp.title = $this.attr('name');
temp.description = $this.find('description').text();
temp.choices = [];
var counter = 0;
$this.find('tasks').eq( counter ).each(function(index, child) {
document.write( $(child).find("task").text() + counter + "<br>");
counter++;
});
});
});
我想看到的任务子级的输出:
Do this0
Do that1
Do other2
Do something3
我目前看到的输出:
Do thisDo that0
Do otherDo something0
【问题讨论】:
标签: jquery xml xml-parsing