简体   繁体   中英

Whats wrong with my javascript loop returning xml?

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 />' );


}

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) +  /* ... */ );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM