显示星期几的javascript

时间:2014-03-24 16:50:12

标签: javascript jquery

我想在列表中显示一周中的几天。对于今天,我想显示今天这个词。我怎么能用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>

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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

答案 2 :(得分: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'
    }
 });