使用循环创建多个HTML元素

时间:2014-01-15 14:51:20

标签: javascript jquery html jsplumb

我目前有这个: 如您所见,这两个框是硬编码的。

使用给定的XML文件创建这两个框的最简单方法是什么?

<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>

top是这里的“top”,所以是“left”而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看到了这个示例,但是document.write不起作用,框不会被绘制。

1 个答案:

答案 0 :(得分: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。随意提出进一步的问题。