Create one list item for each year using JQuery
I am building a web app that is a visual representation of data sorted by year, and currently have an ordered list of years in the html, i.e.:
<ol id="years">
<li>1900</li>
<li>1901</li>
<li>1902</li>
&h开发者_Python百科ellip;
<li>1950</li>
</ol>
I would prefer that the list was automatically generated on page load by javascript, as it's likely that the year range will change over time, and I don't want to risk the javascript and HTML getting out of sync.
For other functions I am already declaring variables firstYear
and lastYear
that match up to the first and last items in that list, i.e.:
var firstYear = 1900;
var lastYear = 1950;
I've tried to base some code on what looks like a similar question but have not quite figured out how to adapt it properly to my app's requirements.
If anyone can help me write the function to do this, it would be greatly appreciated.
Try this :
var firstYear = 1900;
var lastYear = 1950;
for(var i =firstYear; i<=lastYear; i++) {
$('#years').append('<li>'+i+'</li>')
}
$(document).ready(function() {
var firstYear = 1900;
var lastYear = 1950;
for (var i = firstYear; i++; i <= lastYear) {
$('<li>' + i + '</li>').appendTo('ol#years');
}
});
Do you mean you want to generate the number of years in between given the start and stop year?
<ul id='years'>
</ul>
var startYear = 1950;
var endYear = 1965;
var $years = $('#years');
for (var i = startYear; i <= endYear; i++) {
$years.append('<li>' + i + '</li>');
}
You can do like this
function createYearList(start, end){
var ul = $('<ul>').appendTo('body');
for (i = start; i <= end; i++)
{
$('<li>').html(i).appendTo(ul);
}
}
$(document).ready(function(){
createYearList(1900, 1950);
});
Demo: http://jsfiddle.net/ynhat/ngmNF/
for(var y=1900; y <= 1950; ++y)
$('#years').append('<li>' + y + '</li>');
Seen running here: http://jsfiddle.net/qDAVA/4/
精彩评论