I get returned from the server more than 50 items in my xml response. I know it would be better to handle on the server but this is a request:
Make 2 lists with open <ul> and closing <\ul> each of them has 10 items from the response. No ordering just counting from beginning.
My loop now look like this:
var strHtml = '<ul>';
$(xml).find('Books row').each(function()
{
strHtml += '<li><a href ="mylink">sometext</a></li>';
// ...
});
strHtml += '<\ul>';
$('#category').empty().append(strHtml);
What i need is 2 lists, so i have to handle open and close UL tag in the loop.
Something like this, but i’m not sure if i’m doin it allright:
var itemCounter = 1,
strHtml ='';
$(xml).find('Books row').each(function() //note: function( index )
{
if (itemCounter == 1){
// first iteration opens <ul>
strHtml += '<ul>';
}
else if(itemCounter > 10){
// 10th list item created.
// close first UL and open next UL
strHtml += '</ul><ul>';
}
else if(itemCounter > 20){
// max items allowed detected
// close <ul> and break loop
strHtml += '</ul>';
return;
}
// regular li
strHtml += '<li><a href ="mylink">sometext</a></li>';
itemCounter++;
});
$('#category').empty().append(strHtml);
How would you handle this?
sidenote:
my html/css structure needs to have 2 vertical side by side lists. I found the best result to be in two and float them left, instead of having one list and floating every single item.
All that opening and closing and checking the counter stuff seems a bit fiddly, and also this line:
will be true every time once the counter is above
10so it’ll never go into the finalelse ifblock.I’d put all the li elements into a single array and then just
.slice()out of the array and.join():Demo: http://jsfiddle.net/nRtmj/1/
Note that because I’ve done the
.slice()and.join()in a loop you can easily create additional ul elements if you change the first loop so that it doesn’t stop at 20 elements: http://jsfiddle.net/nRtmj/2/ or if you want to change the number of elements per list just change the10to something else: http://jsfiddle.net/nRtmj/3/