Whats wrong with my javascript loop returning xml?

Johann Taljaard

I have something wrong with my loop as it is returning all the name, link, image and content in one go instead of looping through evey event individually

var items=xml.getElementsByTagName('event').length;
//alert(items);
var name, link, image, content;

for (var i = 0; i < items; i++) {
    //alert('in the loop');
    name = $(xml).find('name').text();
    link = $(xml).find('url').text();
    image = $(xml).find('image').text();
    content = $(xml).find('content').text();

    $('#headername')
    .append('<h3>' + name + '</h3><br /><img src="' + image + '" alt="' + name +'" width="100%"><br /><p>' + content 
            + '</p><h4>Read more at: </h4><a rel="external" data-role="button" data-inline="true" data-icon="back" onclick="doOpen(&#39;' + link + '&#39;, &#39;_blank&#39;);">' +name +'</a><br />' );


}
Cameron

The problem is that $(xml).find('el') returns the first element found every time through the loop, whereas you want the nth one on the nth iteration.

Try this instead:

for (var i = 0; i < items; i++) {
    name = $(xml).find('name').eq(i).text();
    //                        ^^^^^^
    // ...
}

Note also that it's not a very good idea to build HTML using +, since the data could contain HTML characters. They should be escaped with escape:

.append('<h3>' + escape(name) +  /* ... */ );

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related