2014-01-15 106 views
0

我目前有這個: 正如您所看到的,這兩個框是硬編碼的。用循環創建多個HTML元素

什麼是使用給定的XML文件創建這2個盒子的最簡單方法?

<collection> 
<beanRepresentation> 
<beanRepId>222</beanRepId> 
<beanRepName>Bean 1</beanRepName> 
<top>0</top> 
<left>0</left> 
<height>0</height> 
<width>0</width> 
</beanRepresentation> 

<beanRepresentation> 
<beanRepId>223</beanRepId> 
<beanRepName>Bean 2</beanRepName> 
<top>0</top> 
<left>0</left> 
<height>0</height> 
<width>0</width> 
</beanRepresentation> 

</collection> 

頂部的「頂」這裏面,所以「左」和beanRepId是「ID」:

<div class=" normal" id="1" 
         style="text-align:left; 
         top: 13em; 
         left: 5em; 
         height: 10em; 
         width: 12em;"> 

我看到這個例子從http://www.w3schools.com/xml/tryit.asp?filename=tryxml_display_table但文件撰寫不工作,盒子不會被繪製。

回答

1

你可以找到一個工作示例here。請注意,我修改了XML文件。腳本看起來如下

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
} else {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
} 

xmlhttp.open("GET","catalog.xml",false); 
xmlhttp.send(); 
xmlDoc=xmlhttp.responseXML; 

var x=xmlDoc.getElementsByTagName("beanRepresentation"); 
for (i=0;i<x.length;i++) { 
    document.write("<div class=\"normal\" id=\""); 
    document.write(x[i].getElementsByTagName("beanRepId")[0].childNodes[0].nodeValue); 
    document.write("\" style=\"text-align:left;\ top:"); 
    document.write(x[i].getElementsByTagName("top")[0].childNodes[0].nodeValue); 
    document.write("em; left:"); 
    document.write(x[i].getElementsByTagName("left")[0].childNodes[0].nodeValue); 
    document.write("em; height:"); 
    document.write(x[i].getElementsByTagName("height")[0].childNodes[0].nodeValue); 
    document.write("em; width:"); 
    document.write(x[i].getElementsByTagName("width")[0].childNodes[0].nodeValue); 
    document.write("em;\"></div>"); 
} 

它是根據您鏈接到w3schools example。隨意提出進一步的問題。

+0

所以我假設你對XML的修改是位置?所以他們不堆疊在一起?盒子的高度和寬度是否正確? – PhoonOne

+0

你說得對。我只是想確保腳本獲得正確的值,不幸的是,在XML示例中,您提到的那些值被設置爲0。不過,您可以查看XML文件[here](http://cdn.florianbussmann.de/stackoverflow/21140602_catalog.xml)。 –

+0

好的謝謝。另一個問題是我不知道我是否首先檢索xml文件。出於測試目的,我使用了:xmlhttp.open(「GET」,「http://cdn.florianbussmann.de/stackoverflow/21140602_catalog.xml」,false);這應該工作嗎? – PhoonOne