我正在练习XML,Javascript。我想连续显示每只动物的图像。但我的主要问题是图像中的嵌套不均匀。有些有两个图像,有些有4个。我有XML文件如下:
<zoo>
<animal>
<common_name>Elephant</common_name>
<images>
<image>elephant13.jpg</image>
</images>
</animal>
<animal>
<common_name>Emu</common_name>
<images>
<image>emu12.jpg</image>
<image>emu26.jpg</image>
<image>emu23.jpg</image>
</images>
</animal>
<animal>
<common_name>Lion</common_name>
<images>
<image>lion51.jpg</image>
<image>lion46.jpg</image>
</images>
</animal>
<zoo>`
我的img的javascript是:
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
images.src ="images/" + zooRoot.getElementsByTagName("image")[i].firstChild.nodeValue;
ul.appendChild(images);
}
}
答案 0 :(得分:0)
试试这个。这个获取是xml的文档节点,并从中查询图像。获得数组后,迭代它并从节点获取内部文本。 var xmlimages = xml.getElementsByTagName('image');
if (getNumberWithdrawals() > 3)
答案 1 :(得分:0)
尝试将Animal作为对象,然后创建一个HTMLstring并将其插入节点;
var animalsNode = zooRoot.getElementsByTagName('animal');
var animals = [];
for(var i=0; i<animalsNode.length; i++){
var animalName = animalsNode[i].getElementsByTagName("common_name").innerHTML;
var animalImageNodes = animalsNode[i].getElementsByTagName("image");
var animalImages = [];
//will store image paths into animalImages
for(var j=0; j<animalImageNodes.length; j++){
animalImages.push("image/" + animalImageNodes.innerHTML);
}
animals.push({
common_name: animalName,
images: animalImages //array of image urls
})
}
var animalsHTML = function(animals){
//lets cereate string with "html table"
var animalsHtml = "<table>";
for(var i=0; i<animals.length; i++){
animalsHtml += "<tr>";
animalsHtml += "<td>" + animals[i].name + "</td>"
+ "<td><img src='" + animals[i].images[0] + "' /></td>";
animalsHtml += "</tr>";
}
animalsHtml += "</table>";
return animalsHtml;
}
tableNode.innerHTML = animalsHTML(animals);
或者你可以定义动物数组更多功能方式=)
var animals = zooRoot.getElementsByTagName('animal').map(function(animalNode){
return {
common_name: animalNode.getElementsByTagName('common_name')[0].innerHTML,
images: animalNode.getElementsByTagName('image').map(function(imageNode){
return "image/" + imageNode.innerHTML;
})
};
});
//and more js style of draw-function
var animalsHTML = function(animals){
return "<table>" + animals.reduce(function(curr, next){
return curr + "<tr><td>" + next.name + "</td>"
+ "<td>"
+ next.images.reduce(function(c, n){
return c + "<img src='" + n "' />"
},'')
+ "</td>"
+ "</tr>";
}, '') + "</table>";
}
tableNode.innerHTML = animalsHTML(animals);
我没有测试它,但应该工作=) soory for my English
答案 2 :(得分:0)
请在节点上插入循环:
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
var imgData = zooRoot.getElementsByTagName("image");
for (i = 0; i <imgData.length; i++) {
images.src ="images/" + imgData[i].firstChild.nodeValue;
ul.appendChild(images);
}
}
}