我是javascript / jQuery的新手,正在尝试一些对自己的技能水平抱有雄心的东西。我发现一些片段虽然有所帮助,但却被困住了。
我有一堆这样的日期:dd-month-yyyy(2013年10月10日)。据我了解,这在某种程度上是一种非常规的日期格式。因此,我想做的是将日期解析为普通格式,然后使用jQuery tinysort插件(我认为使用不正确)来安排父div。
我在这里做了一个jsfiddle:http://jsfiddle.net/8BYDZ/
或者这是我的代码:
<div id="date-sort">
<div class="date-content">
<p>Some Content</p>
<p class="date-sort">10-Oct-2013</p>
<hr />
</div>
<div class="date-content">
<p>Some Content</p>
<p class="date-sort">12-Oct-2013</p>
<hr />
</div>
<div class="date-content">
<p>Some Content</p>
<p class="date-sort">2-Sep-2013</p>
<hr />
</div>
<div class="date-content">
<p>Some Content</p>
<p class="date-sort">22-Jun-2013</p>
<hr />
</div>
<div class="date-content">
<p>Some Content</p>
<p class="date-sort">1-May-2013</p>
<hr />
</div>
</div>
$(document).ready(function(){
function customParse(str) {
var months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'],
n = months.length, re = /(\d{2})-([a-z]{3})-(\d{4})/i, matches;
while(n--) { months[months[n]]=n; } // map month names to their index :)
matches = str.match(re); // extract date parts from string
return new Date(matches[3], months[matches[2]], matches[1]);
}
var array = [];
var elements = $('.date-sort');
for(var i = 0; i < elements.length; i++) {
var current = elements[i];
if(current.children.length === 0 && current.textContent.replace(/ |\n/g,'') !== '') {
// Check the element has no children && that it is not empty
customParse(current.textContent);
array.push(current.textContent);
}
}
$('div#date-sort>.date-content>.date-sort').tsort();
});
感谢您的帮助,见解或投入。
最佳答案
您需要给tinysort一个可排序的日期。
new Date(matches[3], months[matches[2]], matches[1]).toJSON();
// ...
current.setAttribute('data-date', customParse(current.textContent));
// ...
$('div#date-sort>.date-content').tsort('.date-sort', {attr: 'data-date' });
您的正则表达式过于严格,因为天数并不总是两个数字。
re = /(\d{1,2})-([a-z]{3})-(\d{4})/i
Here is a working jsiddle