jQuery从单个和多个标签解析xml [英] jquery parse xml from single and multiple tags
问题描述
遇到了从xml节点返回文本的问题.所有这一切都必须是动态的.这是xml:
Got a problem returning the text from an xml node. It all needs to be dynamic. Here is the xml:
<instructions>Some ins text.</instructions>
<options>
<option>1.png</option>
<option>2.png</option>
<option>3.png</option>
<option>4.png</option>
</options>
<noOfOptions>4</noOfOptions>
这是jquery的解析代码:
Here is the jquery parse code:
currentPageData.push({
title:$(xml).find("page").attr("name"),
noOfOptions:$(xml).find("noOfOptions").text(),
text:$(xml).find("text").text(),
instructions:$(xml).find("instructions").text(),
option:$(xml).find("option").each(function() {
$(this).text();
}),
问题在于选项部分.这仅返回一个对象.我认为这是因为.each函数所致.但是我需要所有它们都存在,并且要返回它们,并且我需要它在这样的for循环中返回文本:
The problem is the option section. This just returns one object. I think this is because of the .each function. But I need all of them, that are present to be returned and i need it to return the text in a for loop like this:
for(i=0;i<noOfOptions;i++) {
currentPageData[0].option[0];
}
以上操作无效.我该如何解决?
The above is not working. How can I fix it?
谢谢!
推荐答案
要获取选项节点的文本内容,请尝试此操作....
To get the text content of your option nodes try this....
首先,您的xml无效.我添加了一个根节点
Firstly, your xml isn't valid. I've added a root node
var xml = "<root>
<instructions>Some ins text.</instructions>
<options>
<option>1.png</option>
<option>2.png</option>
<option>3.png</option>
<option>4.png</option>
</options>
<noOfOptions>4</noOfOptions>
</root>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$options = $xml.find("option"); // get all option nodes
然后使用jquery.each获取每个选项值
Then to get each option value using jquery .each
$.each($options, function() {
console.log($(this).text());
});
希望有帮助
提琴: http://jsfiddle.net/JohnMcNulty/vRf9Z/
这篇关于jQuery从单个和多个标签解析xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!