我有一个包含24个列表项的无序列表。我需要根据一天中的小时重新订购它们。例如:列表项#16需要在下午4点作为列表项#1出现。有什么想法吗?
<ul id="foo2">
<li>12am</li>
<li>1am</li>
<li>2am</li>
<li>3am</li>
<li>4am</li>
<li>5am</li>
<li>6am</li>
<li>7am</li>
<li>8am</li>
<li>9am</li>
<li>10am</li>
<li>11am</li>
<li>12pm</li>
<li>1pm</li>
<li>2pm</li>
<li>3pm</li>
<li>4pm</li>
<li>5pm</li>
<li>6pm</li>
<li>7pm</li>
<li>8pm</li>
<li>9pm</li>
<li>10pm</li>
<li>11pm</li>
</ul>
下午4点,我希望下午4点的李显示为好像是列表中的第一个。我有一个滑块连接到此列表,一次显示4个,并希望从当前小时开始。
这是工作清单/时间表(仍在进行中) http://livestreamchicago.tv/content/lsctv#overlay-context=calendar-created/week/2013-W40
答案 0 :(得分:0)
我建议您从当前小时开始生成列表,而不是对列表进行排序,如下所示。我还添加了a working example on JSBin。
// Sets the inner contents of an HTML element identified by `listId` to a list
// of the next 24 hours starting from the current hour
//
// Example:
//
// <ol id="hour-list"></ol>
// <script>listHours('foo-list')</script>
// <ol id="hour-list"><li>12am</li><li>...</li></ol>
function listHours(listId) {
// Get the current hour from a new Date object
var currentHour = (new Date()).getHours();
// An array to store the list items we generate
var hourList = [];
// Iterate through 24 hours starting from the current hour and add the list
// items to the hour list
var i = 0;
while(i < 24) {
var h = (currentHour + i) % 24;
hourList.push('<li>' + formatHour(h) + '</li>');
i++;
}
// Combine the list items and add them to element targeted by `listId`
document.getElementById(listId).innerHTML = hourList.join('');
}
// Formats an hour (0-23) to an AM/PM format.
//
// Examples:
//
// formatHour(0) // => '12am'
// formatHour(1) // => '1am'
// formatHour(13) // => '1pm'
// formatHour(23) // => '11pm'
function formatHour(hour) {
var fmtHour;
if (hour === 0) {
fmtHour = 12;
} else if (hour > 12) {
fmtHour = hour - 12;
} else {
fmtHour = hour;
}
var ampm = hour < 12 ? 'am' : 'pm';
return fmtHour + ampm;
}