2014-03-24 67 views
-2

我想在列表中显示星期几。在当天,我想显示Today这个词。我怎样才能做到这一点与JavaScript?显示星期几javascript

<ul class="week-days"> 
    <li><a href="#"><span id="firstD">Today</span></a></li> 
    <li><a href="#"><span id="secondD">Tue</span></a></li> 
    <li><a href="#"><span id="thirdD">Wed</span></a></li> 
    <li><a href="#"><span id="forthD">Thu</span></a></li> 
    <li><a href="#"><span id="fifthD">Fri</span></a></li> 
    <li><a href="#"><span id="sixthD">Sat</span></a></li> 
    <li><a href="#"><span id="seventhD">Sun</span></a></li> 
</ul> 
+4

我不明白你想解决的问题。您发布了关于JavaScript的问题,但您发布的唯一代码是标记。你能澄清你的问题吗? –

+0

请参阅http://jsfiddle.net/arunpjohny/C6LKS/1/ –

+0

谢谢@Arun。你的答案是最好的,效果很好。 – user3456282

回答

0

这里有一种方法:

// Find the unordered list element 
var list = $('ul.week-days'); 

// Check what day it is today (0..6) 
var today = (new Date()).getDay(); 

// Our day strings; in JS, "Sunday" is the beginning of the week 
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; 

// Add a list item to the list, substituting "Today" if necessary 
$.each(days, function(i, v) { 
    list.append($('<li>' + (i == today ? 'Today' : v) + '</li>')); 
}); 

当然它缺少<a><span>...</span></a>结构,但我会离开,作为一个练习。

Working jsFiddle Demo

1

您可以通过在页面的底部添加此(正上方的身体结束标记)

<script type="text/javascript"> 
    var i = 1; 
    $('.week-days li').each(function(){ 
     if ((new Date()).getDay() == i) { 
     $(this).val('Today').html('Today'); 
     } 
     i++; 
    }); 
</script> 
0

你可以做这样的事情(做到这一点只有当你到3个字母缩写)

var date = new Date().toString(); // Get the Date and return it as a string 
var day = date.split(' ')[0]; // Split the date and store the first index (day) 
$('.week-days li').each(function(){ // loop over the li 
    if($(this).html() === day){ // if this html is the same as day variable 
     $(this).html('Today'); // change the html to 'Today' 
    } 
});