我使用JavScript和jQuery来读取XML文档并随后使用XML中的信息创建HTML对象。不确定如何设计使用XML创建HTML对象的JavaScript/jQuery功能
XML文档中的主'C'节点都有一个type属性,根据类型我想运行一个函数,该函数将使用分配给该特定'C'节点的其他属性创建一个新的html对象节点。
目前,我有一个for
循环,它从XML中提取每个“C”节点,也是属性(例如宽度,高度,x,y)。
同样在for
循环中,我有一个if
语句,它检查正在处理的当前'C'节点的'type'属性,并根据类型运行不同的函数,然后创建一个新的HTML对象与从XML中绘制的属性。
问题是可能有多个相同类型的'C'节点,所以例如当我创建的函数将在'type = 1'的'C'节点被检测到时运行,我不能使用'var p = document.createElement('p')
',因为如果在循环的稍后出现相同类型的'C'节点,它将冲突并用刚刚创建的变量覆盖该元素。
我不太确定如何解决这个问题?
这是我的整个脚本。如果你需要我详细说明任何部件请问,我敢肯定,它不是写在最好的可能的方式:
var arrayIds = new Array();
$(document).ready(function(){
$.ajax({
type: "GET",
url: "question.xml",
dataType: "xml",
success: function(xml)
{
$(xml).find("C").each(function(){
arrayIds.push($(this).attr('ID'));
});
var svgTag = document.createElement('SVG');
// Create question type objects
function ctyp3(x,y,width,height,baC)
{
alert('test');
var r = document.createElement('rect');
r.x = x;
r.y = y;
r.width = width;
r.height = height;
r.fillcolor = baC;
svgTag.appendChild(r);
}
// Extract question data from XML
var questions = [];
for (j=0; j<arrayIds.length; j++)
{
$(xml).find("C[ID='" + arrayIds[j] + "']").each(function(){
// pass values
questions[j] = {
typ: $(this).attr('typ'),
width: $(this).find("I").attr('wid'),
height: $(this).find("I").attr('hei'),
x: $(this).find("I").attr('x'),
y: $(this).find("I").attr('x'),
baC: $(this).find("I").attr('baC'),
boC: $(this).find("I").attr('boC'),
boW: $(this).find("I").attr('boW')
}
alert($(this).attr('typ'));
if ($(this).attr('typ') == '3')
{
ctyp3(x,y,width,height,baC);
// alert('pass');
} else {
// Add here
// alert('fail');
}
});
}
}
});
});
你能发表你的代码的例子吗? – 2010-06-03 14:17:48