开发者

jQuery Calculate Date

Any reason why this is landing on the wrong day?

http://jsfiddle.net/SparrwHawk/MH5wP/

I've written the code below for reference, but it's obviously clearer on jsfiddle

<p>Sun / Closed</p>
<p>Mon / Closed</p>
<p>Tues / 9am – 5pm</p>
<p>Wed / 9am – 5pm</p>
<p>Thurs / 9am – 8pm</p>
<p>Fri / 9.30pm – 6.30pm</p>
<p>Sat / 8.30am – 4.30pm</p>

<script>
// Day where 0 is Sunday
var date = new Date();
var d = (date.getDay());

$(function(){
    if (d = 1) {
        $('p:contains("Mon")').addClass('today');
    } else if (d = 2) {
        $('p:contains("Tues")').addClass('today');
    } else if (d = 3) {
        $('p:contains("Wed")').addClass('today');
    } else if (d = 4) {
        $('p:contains("Thurs")').addClass('today');
    } else 开发者_开发技巧if (d = 5) {
        $('p:contains("Fri")').addClass('today');
    } else if (d = 6) {
        $('p:contains("Sat")').addClass('today');
    } else {
        $('p:contains("Sun")').addClass('today');
    }    
});
</script>


You gotta use double equal signs (==) to check your value of d, otherwise you'll set d=1 with your first if statement and you'll always have a red Monday.


You are using assignement (=) instead of comparison (== or ===) in your if.

So what you are doing is if ( (d = 1) === true ) aka if if you can assign 1 to d. This works, so the code enters your first if and the elses are never touched.

A simple way to make sure not to do that sort of mistake is to reverse the order of the operands when checking against hardcoded values:

$(function(){
  if (1 == d) {
    // do something ...

This way if you mistakenly use =, the assignation fails and you get an error.


You should be able to do something much simpler, like:

$(function()
{
  var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  var day = days[(new Date()).getDay()];
  $('p:contains("' + day + '")').addClass('today');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜