简体   繁体   中英

Hide previous and next month cells from a calendar

I am trying to remove previous and next month dates from the following calendar.

在此处输入图像描述

jQuery('.c-day').each(function() {
    let jqThis = jQuery(this);
    let date = jQuery.trim(jqThis.text());
    console.log(date);
});

The above jQuery code selects all cells. This is what I get.

30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
1
2
3
4
5
6
7
8
9
10

However, I can filter/remove 30 from the beginning and 1 2 3 4 5 6 7 8 9 10 from the end but this does not work with other months like November, December, January etc?

jQuery('.c-day').each(function(i) {
    let jqThis = jQuery(this);
    let date = jQuery.trim(jqThis.text());
    console.log(date);
    if (i == 0 || i > 29) jqThis.hide();
});

Can someone please help me with the logic here?

You can tweak your if statement to get what you want:

jQuery('.c-day').each(function(i) {
    let jqThis = jQuery(this);
    let date = jQuery.trim(jqThis.text());
    console.log(date);
    if (i == 0 || (i > 29 && date < 12)) jqThis.hide();
});

What this change does (i > 29 && date < 12) is using both the index and the date you already have. If the index if above 29 it means that it probably is from the next month, but we can't be sure since some months have 30 days and some 31. So we check for date . If the value is below 12 it means it's from the next month.

I chose 12 since I think no calendar will show more than 12 days from next month, but you can modify it if I'm wrong, a value up to 20 or something would work equally well.


Since December has many days from the previous month, a different logic is necessary, which should always work:

jQuery('.c-day').each(function(i) {
    let jqThis = jQuery(this);
    let date = jQuery.trim(jqThis.text());
    let dayCounter = 1;
    console.log(date);
    if (date > dayCounter || date < dayCounter){
      jqThis.hide();
    } else {
      dayCounter++;
    }

});

This works by knowing that all days from the previous month will be bigger than day 1, and all days from next month will be smaller than the last day of the month. We keep track of the day we're on, so the days of this month are never hidden.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM