Unsure how to design JavaScript / jQuery functionality which uses XML to create HTML objects
Posted
by Jack Roscoe
on Stack Overflow
See other posts from Stack Overflow
or by Jack Roscoe
Published on 2010-06-03T14:15:24Z
Indexed on
2010/06/03
14:24 UTC
Read the original article
Hit count: 261
Hi,
I'm using JavScript and jQuery to read an XML document and subsequently use the information from the XML to create HTML objects.
The main 'C' nodes in the XML document all have a type attribute, and depending on the type I want to run a function which will create a new html object using the other attributes assigned to that particular 'C' node node.
Currently, I have a for
loop which extracts each 'C' node from the XML and also it's attributes (e.g. width, height, x, y).
Also inside the for
loop, I have an if
statement which checks the 'type' attribute of the current 'C' node being processed, and depending on the type it will run a different function which will then create a new HTML object with the attributes which have been drawn from the XML.
The problem is that there may be more than one 'C' node of the same type, so for example when I'm creating the function that will run when a 'C' node of 'type=1' is detected, I cannot use the 'var p = document.createElement('p')
' because if a 'C' node of the same type comes up later in the loop it will clash and override that element with that variable that has just been created.
I'm not really sure how to approach this?
Here is my entire script. If you need me to elaborate on any parts please ask, I'm sure it's not written in the nicest possible way:
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');
}
});
}
}
});
});
© Stack Overflow or respective owner