2013-09-23 58 views
-5

我有一個包含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

+3

請告訴我們列表的標記,你試圖完成你的任務是什麼。 – Bergi

+1

目前的順序不會改變使用排序... :) – Johan

+3

他們都是''如何排序他們會有所作爲? –

回答

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; 
} 
+0

這個很好用!我唯一需要做的不同是不顯示當前時間,而是在當前時間顯示文本或HTML代碼。任何幫助調整,所以我可以自定義列表? – Daniel

+0

更清晰,我打算在每個列表項中放置php代碼,以便從我們正在使用的日曆中提取信息。 – Daniel

+0

考慮到您的用例,您應該使用PHP而不是JavaScript對列表進行排序,因爲您的用戶可能處於不同的時區。 – fny