[英]Only get part out of data-attribute
我只想知道這個時間:
data-timestamp="2014/04/01 10:50:01";
$(items).each(function(){
var timestamp = $(this).data('timestamp');
$(this).wrap("<div class='" + timestamp + "'></div>");
});
這包裝了他們自己的時間戳內的所有項目所以class="2014/04/01 10:50:01"
所以包裝部分應該只包裹時間戳小時所以10 class="10"
- 我無法弄清楚如何做這個。
items是一個包含div的數組,它們都包含具有不同時間的時間戳。
您可以將字符串日期轉換為實際日期:
var d = Date(timestamp);
然后從d
日期算起
var hour = d.getHours();
所以你的代碼就像這樣:
$(items).each(function(){
var hour = new Date($(this).data('timestamp')).getHours();
$(this).wrap("<div class='" + hour + "'></div>");
});
或者看起來有點復雜
$(items).each(function(){
var date = new Date($(this).data('timestamp')); // turn into a date
var hour = date.getHour(); // get the hour 0 = midnight
$(this).wrap("<div class='" + hour + "'></div>");
});
您可以在Javascript中使用內置日期格式,然后在此數據對象上使用方法.getHours()。
$(items).each(function(){
var timestamp = $(this).data('timestamp');
var d = new Date(timestamp);
$(this).wrap("<div class='" + d.getHours()+ "'></div>");
});
如果您的格式始終相同並且不想將其解析為日期,則可以使用子字符串:
$(items).each(function(){
var timestamp = $(this).data('timestamp').substr(11, 2);
$(this).wrap("<div class='" + timestamp + "'></div>");
});
你可以使用.split()
$(items).each(function () {
var timestamp = $(this).data('timestamp');
timestamp = timestamp.split(" ");
timestamp = timestamp[1].split(":");
timestamp = timestamp[0];
$(this).wrap("<div class='" + timestamp + "'></div>");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.