I have a for-loop in javascript/jQuery to create an html unordered list. I want every multiple of 10 iteration to be a new unordered list tag.
JavaScript code:
var count = 100;
for(var i = 0; i <= count; i++) {
if(i == 0) {
$('ul.list').append('<li>' + i + '</li>');
} else {
if(i % 10 == 0) {
$('ul.list').after('<ul class="list"></ul>');
}
$('ul.list:last-child').append('<li>' + i + '</li>');
}
}
It looks like it should work, but JavaScript generates this:
<ul class="list"><li>0</li></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
<ul class="list"></ul>
...
I expect it to output 10 <li>
items and then create a new unordered list tag every 10th item. Clearly the code is all wrong. Can I get some help.
I would be more inclined to build a string with the HTML, then post it one time.
Try ...
var max = 100;
var HTML = ["<ul class='list'>"];
for (var i=0,len=max; i<len; i++) {
HTML.push("<li>" + i + "</li>");
if (i%10===0 && (i!==0) {
HTML.push("</ul>");
HTML.push("<ul class='list'>");
}
}
HTML.push("</ul>");
$("#lists").html(HTML.join("\n");
Basically, I've built an array of the html code needed, then merged it into one string with line breaks \\n
as I placed it into the DOM.
The if
inside the loop closes the <ul>
and opens a new one, but NOT on the zero (first step in the loop).
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.